操作员 ?。和扩展方法
Operator ?. and extension methods
使用 .
运算符的扩展方法总是被调用,即使对象为 null 而没有抛出 NullReferenceException
。通过使用 operator ?.
它永远不会被调用。例如:
using System;
public class Program
{
public static void Main()
{
A a = null;
a.b(); // works
a?.b(); // doesn't work
}
}
public class A { }
public static class ext
{
public static void b(this A a)
{
Console.WriteLine("I'm called");
}
}
为什么在这种情况下不调用扩展方法?这是一个模棱两可的功能吗?
你的表达式 a?.b() 使用
?. 运算符转换为等价物:
if(a != null)
{
a.b();
}
这就是为什么你的方法没有被调用的原因。
使用 .
运算符的扩展方法总是被调用,即使对象为 null 而没有抛出 NullReferenceException
。通过使用 operator ?.
它永远不会被调用。例如:
using System;
public class Program
{
public static void Main()
{
A a = null;
a.b(); // works
a?.b(); // doesn't work
}
}
public class A { }
public static class ext
{
public static void b(this A a)
{
Console.WriteLine("I'm called");
}
}
为什么在这种情况下不调用扩展方法?这是一个模棱两可的功能吗?
你的表达式 a?.b() 使用 ?. 运算符转换为等价物:
if(a != null)
{
a.b();
}
这就是为什么你的方法没有被调用的原因。