gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:05:05 26 4
gpt4 key购买 nike

我们希望避免出现 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com