gpt4 book ai didi

c# - 如何在 C# 中有条件地转换为多种类型

转载 作者:太空狗 更新时间:2023-10-30 00:31:51 24 4
gpt4 key购买 nike

我正在查看具有这种模式的函数:

if( obj is SpecificClass1 )
{
((SpecificClass1)obj).SomeMethod1();
}
else if( obj is SpecificClass2 )
{
((SpecificClass2)obj).SomeMethod2();
}
else if( obj is SpecificClass3 )
{
((SpecificClass3)obj).SomeMethod3();
}

并得到一个代码分析警告:CA1800 Do not cast unnecessarily。

有什么好的代码模式可以用来替换这段代码,既高效又简洁。

更新

我没说,obj是用object类型声明的。

我最初在这里问了两个问题。我已经拆分了一个(反正还没有人回答):Why wouldn't the compiler optimize these two casts into one?

最佳答案

界面

最好的方法是引入一个所有类型都实现的接口(interface)。这只有在签名匹配时才有可能(或者您没有太多差异)。

用作

如果创建接口(interface)不是一个选项,您可以使用以下模式摆脱 CA 消息(尽管这也会引入不必要的强制转换,因此会稍微降低性能):

var specClass1 = obj as SpecificClass1;
var specClass2 = obj as SpecificClass2;
var specClass3 = obj as SpecificClass3;
if(specClass1 != null)
specClass1.SomeMethod1();
else if(specClass2 != null)
specClass2.SomeMethod2();
else if(specClass3 != null)
specClass3.SomeMethod3();

也可以改成这样的结构(我个人认为上面的可读性更好):

var specClass1 = obj as SpecificClass1;
if (specClass1 != null)
specClass1.SomeMethod1();
else
{
var specClass2 = obj as SpecificClass2;
if (specClass2 != null)
specClass2.SomeMethod2();
else
{
var specClass3 = obj as SpecificClass3;
if (specClass3 != null)
specClass3.SomeMethod3();
}
}

在字典中注册类型

另外,如果你有很多类型要检查,你可以在字典中注册它们并检查字典的条目:

var methodRegistrations = new Dictionary<Type, Action<object> act>();
methodRegistrations.Add(typeof(SpecificClass1), x => ((SpecificClass1)x).SomeMethod1());
methodRegistrations.Add(typeof(SpecificClass2), x => ((SpecificClass2)x).SomeMethod2());
methodRegistrations.Add(typeof(SpecificClass3), x => ((SpecificClass3)x).SomeMethod3());

var registrationKey = (from x in methodRegistrations.Keys
where x.IsAssignableFrom(obj.GetType()).FirstOrDefault();
if (registrationKey != null)
{
var act = methodRegistrations[registrationKey];
act(obj);
}

请注意,注册很容易扩展,您还可以在操作中调用具有不同参数的方法。

关于c# - 如何在 C# 中有条件地转换为多种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21987025/

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