pattern matching is C# 7.0
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is
原来的版本
private static string DateTimeFormat(DateTime date) { string result = string.Empty; if (Logger == null) { return result; } var appenders = GetAppenders(); var appender = appenders.FirstOrDefault(x => x is RollingFileAppender) as RollingFileAppender; if (appender != null) { result = date.ToString(appender.DatePattern, DateTimeFormatInfo.InvariantInfo); } else { result = date.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo); } return result; }
优化后的版本
private static string DateTimeFormat(DateTime date) { string result = string.Empty; if (Logger == null) { return result; } var appenders = GetAppenders(); if (appenders.FirstOrDefault(x => x is RollingFileAppender) is RollingFileAppender appender) { result = date.ToString(appender.DatePattern, DateTimeFormatInfo.InvariantInfo); } else { result = date.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo); } return result; }
涉及到的新知识点
Type pattern
When using the type pattern to perform pattern matching, is
tests whether an expression can be converted to a specified type and, if it can be, casts it to a variable of that type. It is a straightforward extension of the is
statement that enables concise type evaluation and conversion. The general form of the is
type pattern is:
expr is type varname
where expr is an expression that evaluates to an instance of some type, type is the name of the type to which the result of expr is to be converted, and varname is the object to which the result of expr is converted if the is
test is true
.
The is
expression is true
if any of the following is true:
-
expr is an instance of the same type as type.
-
expr is an instance of a type that derives from type. In other words, the result of expr can be upcast to an instance of type.
-
expr has a compile-time type that is a base class of type, and expr has a runtime type that is type or is derived from type. The compile-time type of a variable is the variable's type as defined in its declaration. The runtime type of a variable is the type of the instance that is assigned to that variable.
-
expr is an instance of a type that implements the type interface.
If exp is true
and is
is used with an if
statement, varname is assigned and has local scope within the if
statement only.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2015-04-11 C#中的转换