Kyl*_*Mit 5 c# pattern-matching c#-7.0
我想抓住可枚举的第一个实例,然后在找到的实例上执行一些操作(如果它存在(!= null)).有没有办法简化C#7模式匹配的访问?
采取以下起点:
IEnumerable<Client> clients; /// = new List<Client> {new Client()};
Client myClient = clients.FirstOrDefault();
if (myClient != null)
{
// do something with myClient
}
Run Code Online (Sandbox Code Playgroud)
我可以将呼叫FirstOrDefault与这样的if statement事情结合起来:
if (clients.FirstOrDefault() is null myClient)
{
// do something with myClient
}
Run Code Online (Sandbox Code Playgroud)
我没有在MSDN模式匹配或Stack Overflow上的其他地方看到任何类似的示例
你绝对可以做到这一点.我的例子使用string但它可以使用相同的Client.
void Main()
{
IList<string> list = new List<string>();
if (list.FirstOrDefault() is string s1)
{
Console.WriteLine("This won't print as the result is null, " +
"which doesn't match string");
}
list.Add("Hi!");
if (list.FirstOrDefault() is string s2)
{
Console.WriteLine("This will print as the result is a string: " + s2);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1523 次 |
| 最近记录: |