【发布时间】:2020-01-31 12:40:07
【问题描述】:
我不知道它到底叫什么,但现在我将它称为“非空测试”。在 C# 8 中,有一个新行为允许测试对象是否不为空,例如:
Foo foo = new Foo();
if(foo is { })
{
//foo is not null
}
你也可以从这个对象中提取属性:
public class Foo
{
public int Bar { get; set; }
}
Foo foo = new Foo();
if(foo is { Bar: var bar })
{
//Foo is not null and bar contains the value of the property of the foo instance
}
到目前为止一切顺利,但我想它类似于这样:
public bool GetBar(Foo foo, out int bar)
{
if(foo is null)
{
return false;
}
bar = foo.Bar;
return true;
}
这将被用作这样的东西:
Foo foo = new Foo();
if(GetBar(foo, out var bar))
{
//Foo is not null and bar contains the value of the property of the foo instance
}
现在我的实际问题是:有什么方法可以使用 ref 的行为吗?看起来像这样:
if(foo is { Bar: ref var bar })
{
//Foo is not null and bar contains the value of the property of the foo instance
}
如果这不存在,我会理解,因为out ref 也不存在。那么有什么方法可以做到这一点,或者有什么反对它的吗?
【问题讨论】:
-
据我了解,{ } 的符号表示“某个对象”。对象没有引用变量的概念。 ref 关键字用于函数参数。所以答案是否定的
-
好吧,我只是用 ref 来举例说明我的意思。