简体   繁体   English

在 if 条件中声明一个变量以在 C# 中进一步测试

[英]Declaring a variable in the if condition for further testing in C#

I've seen it done before in ac# tutorial but I can't seem to find it again.我之前在 ac# 教程中看到过它,但我似乎无法再次找到它。

Take this code for example:以这段代码为例:

public class Order
{
    public  OrderItem Item { get; set; }
}

public class OrderItem
{
    public string Name { get; set; }
}


public void SomeMethod(object obj)
{
    if(obj is Order && ((Order)obj).Item !=null)
    {
        Console.WriteLine(((Order)obj).Item.Name);
    }
}

The shorthand I'm looking for looks something like this我正在寻找的速记看起来像这样

public void SomeMethod(object obj)
{
    if (myObj = obj is Order && myItem = myObj.Item != null)
    {
        Console.WriteLine(myItem.Name);
    }
}

I'm not able to find the correct syntax for that我找不到正确的语法

You are looking for pattern matching .您正在寻找模式匹配

With property patterns (C# 8.0) you can do something like this:使用属性模式 (C# 8.0),您可以执行以下操作:

if (obj is Order { Item: { } } order)
{
    Console.WriteLine(order.Item.Name);
}

This will check that obj is an Order and it has non-null Item (via "empty" property pattern ) and if both result in true will execute the code block using typed variable order .这将检查obj是否是一个Order并且它具有非空Item (通过“空”属性模式),如果两者的结果都为 true 将使用类型化变量order执行代码块。

Or even next:甚至下一个:

if (obj is Order { Item: { } item })
{
    Console.WriteLine(item.Name);
}

Basically the same but will use item variable for non-null item.基本相同,但将对非空项目使用item变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM