是否有(Object AS Class)块(C#)之类的东西 [英] Is there something like an (Object AS Class) Block (C#)

查看:76
本文介绍了是否有(Object AS Class)块(C#)之类的东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是一个真正的问题,但是我有一些代码.它由一个抽象类Part组成,该类具有2个扩展类,分别称为ContentPart和MultiPartPart.

现在我有很多行,如:

It is not a real issue, but i have some code. That consists of an abstract class Part with 2 extension classes to it called ContentPart and MultiPartPart.

now i have a lot of lines like :

Part part;
if (part is MultiPartPart){
    (part as MultiPartPart).obj1 = x;
    (part as MultiPartPart).obj2 = y;
    (part as MultiPartPart).obj3 = z;
}



当然,我可以制作一个新的MultiPartPart对象,然后将传递对象复制到该对象上...但这是不可能的,因为复制该对象只会消耗更多的东西而没有任何附加值.

但是在C#中是否有类似"as"块的内容?就像using块一样?

我现在如何获得代码就像一个魅力,但是它只是将所有这些页面填充为转换..



Off course I could make a new MultiPartPart object and copy the pass object to it... But that is kind of out of the question, because copying the object would be just consuming more without any additional value.

but is there something like an "as" block in c#? Just like a using block?

it works like a charm how i got the code right now, but its just pagefilling all those as conversions..

Thanks in advance!

推荐答案

不,没有.

但是您(可能)在创建对象方面是错误的.我会这样:
No, there isn''t.

But you are (possibly) wrong about creating an object. I would do it like this:
MultiPartPart mpp = part as MultiPartPar;
if (mpp != null)
   {
   mpp.obj1 = x;
   mpp.obj2 = y;
   mpp.obj3 = z;
   }

原因是mpp只是一个引用变量,因此很有可能由JIT编译器最终将其优化为硬件寄存器,而您使用的版本则需要每个调用一个方法之所以使用它,是因为编译器不知道强制转换操作没有您要依赖的副作用.

The reason being that mpp is just a reference variable, so there is a good chance it will be optimised into a hardware register (eventually) by the JIT compiler, whereas the version you use requires a method call each time it is used because the compiler does not know that the cast operation does not have side effects you are relying on.


这篇关于是否有(Object AS Class)块(C#)之类的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆