如何有条件地转换为多种类型在C# [英] How to conditionally cast to multiple types in c#
本文介绍了如何有条件地转换为多种类型在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我期待在这种模式功能:
I'm looking at a function with this pattern:
if( obj is SpecificClass1 )
{
((SpecificClass1)obj).SomeMethod1();
}
else if( obj is SpecificClass2 )
{
((SpecificClass2)obj).SomeMethod2();
}
else if( obj is SpecificClass3 )
{
((SpecificClass3)obj).SomeMethod3();
}
和得到一个代码分析警告:CA1800非必要,请勿投
and get a code analysis warning: CA1800 Do not cast unnecessarily.
什么是我可以用它来替换这个代码,这将是高性能和简洁的好代码模式。
What's a good code pattern I can use to replace this code with that will be performant and concise.
更新
我没有说,但OBJ声明与类型的对象。
I didn't say, but obj is declared with type object.
我最初问了两个问题在这里。我已经拆一关(其中没有人尚未反正回答):的为什么不编译器优化这两个类型转换成一个?
I originally asked two questions here. I've split one off (which nobody had yet answered anyway): Why wouldn't the compiler optimize these two casts into one?
推荐答案
如何编写方法
public static class ObjectExtensions
{
public static bool TryCast<T>(this object from, out T to) where T : class
{
to = from as T;
return to != null;
}
}
和使用它:
SpecificClass1 sc1;
SpecificClass2 sc2;
SpecificClass3 sc3;
if( obj.TryCast(out sc1) )
{
sc1.SomeMethod1();
}
else if( obj.TryCast(out sc2) )
{
sc2.SomeMethod2();
}
else if( obj.TryCast(out sc3) )
{
sc3.SomeMethod3();
}
这篇关于如何有条件地转换为多种类型在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文