c# - 转换时避免 NullReferenceException 的首选做法?

标签 c# casting nullreferenceexception

我们希望避免出现 NullReferenceException。目前我们有:

ISomeInterface interface = this.GetISomeInterfaceInstance();
(interface as ClassImplmentsISomeInterface).Method();

这工作正常,但存在 NullReferenceException 风险。一种解决方案是:

ISomeInterface interface = this.GetISomeInterfaceInstance();
ClassImplmentsISomeInterface instance = interface as ClassImplmentsISomeInterface;
if (instance != null)
    instance.Method();

但是这会产生大量额外的代码用于简单检查(根据 resharper 有 100 种可能的 NRE。)第二种解决方法是:

ISomeInterface interface = this.GetISomeInterfaceInstance();
if (interface is ClassImplmentsISomeInterface)
    (interface as ClassImplmentsISomeInterface).Method();

但我收集到 is 实际上在后台使用 as,因此进行了两次转换,我想避免这种情况。这有关系吗?例如,C# 编译器是否足够聪明来优化这个性能问题?

我还缺少其他一些技巧吗?还是上述方法中的一种更可取?

最佳答案

我能想到一个能让你的代码更短的好方法:

public static void InvokeIfIsT<T>(object o, Action<T> action)
{
    if (o is T)
       action((T)o);
}

像这样使用它:

ISomeInterface interface = this.GetISomeInterfaceInstance();
InvokeIfIsT<ClassImplmentsISomeInterface>(interface, i => i.Method());

关于c# - 转换时避免 NullReferenceException 的首选做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11984043/

相关文章:

c# - 表示百分比、概率或库存水平

c# - Azure:无法执行套接字上的操作,因为系统缺乏足够的缓冲区空间或队列已满

java - 通用接口(interface)类型转换

c# - DateTimeFormatInfo.CurrentInfo 怎么可能为空

c# - 在 C# 中解决全局热键处理的最佳方法?

c# - 异步/等待 Entity Framework ObjectContext 处置

java - 无法将 <Object, Map<Object, Object>> Map 转换为更具体类型的 Map

C# - 转换为基本类型如何工作?

c# - 如何执行空检查?