用is和as进行C#强制转换 [英] c# casting with is and as
本文介绍了用is和as进行C#强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一些帮助.这很容易.我有这段代码,我想讨论一下它是否正确,或者您是否建议一种更好的方法.我对答案有一个主意,但我希望看到您的答案.在这里
I need some help. It is pretty easy. I have this piece of code, and I would like to discuss if it is correct, or if you suggest a better way to do it. I have an idea about the answer but I would like to see your answers. here it goes
if (myObject is ClassA)
{
var myObjectA = myObject as ClassA;
myObjectA?.MethodJustInA();
}
else if (myObject is ClassB)
{
var myObjectB = myObject as ClassB;
myObjectB?.MethodJustInB();
myObjectB?.OtherMethodJustInB();
}
我认为没有必要在每次之后都创建一个新对象,只需这样做:
I think there is no need to create a new object after every if, just doing:
(ClassB)myObjectB.MethodJustInB();
并且不需要检查它是否为null,因为它是否在if is内,因为它不为空
And there is no need to check it is null since if it is within the if is because is not null
谢谢
推荐答案
可能有一些优化.
- 如果
myObject是ClassA
,则不需要进行强制转换.相反,您可以直接进行强制转换:var myObjectA =(ClassA)myObject;
. - 既然是这种情况,您只需调用一个方法,就无需分配新变量:
((ClassA)myObject)?. MethodJustInA();
.>li> - 并且由于如果
myObject
为null,则myObject是ClassA
的计算结果为false,因此您无需再次进行检查:((ClassA)myObject).MethodJustInA();
.
- If
myObject is ClassA
, you don't need the soft cast. Instead you can do the cast directly:var myObjectA = (ClassA)myObject;
. - Since that is the case, and you just call a single method, you don't need to assign a new variable:
((ClassA)myObject)?.MethodJustInA();
. - And because
myObject is ClassA
evaluates to false ifmyObject
is null, you don't need to do the check again:((ClassA)myObject).MethodJustInA();
.
所以:
if (myObject is ClassA)
{
((ClassA)myObject).MethodJustInA();
}
else if (myObject is ClassB)
{
var myObjectB = (ClassB)myObject;
myObjectB.MethodJustInB();
myObjectB.OtherMethodJustInB();
}
这篇关于用is和as进行C#强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文