将一个对象转换为另一种类型
我有一个名为 A 的类和一个名为 B 的类
public class A : UserControl { }
public class B : UserControl { }
现在我有一个程序集,其类的函数接受类 A 的对象。该程序集不是由我创建的,因此我没有任何控制权。基本上是第3方集会。
但我想提供 B 类的对象,因为它是有点定制的。请放心,它包含 A 类的所有属性。我如何将 B 类的对象类型转换为 A 类,以便我可以将第 3 方程序集集成到我的项目中,并根据我的需要自定义外观?
如果我这样的东西 (A)objB
这是不允许的。然后我尝试了这个:
UserControl control = objB as UserControl;
A objA = control as A;
但这种情况下的问题是 objA 为空。
为避免混淆:A 类和组件由第 3 方提供。
提前致谢 :)
I have one class named A and one class B
public class A : UserControl { }
public class B : UserControl { }
Now i have one assembly whose class's function accepts objects of class A. This assembly is not created by me so i don't have any control. Basically it is 3rd party assembly.
But i want to supply my objects of class B since it is bit customized. Rest assured it contains all properties of class A. How can i typecast my object of class B to type A so that i can integrate 3rd party assembly in my project as well as customize the look and feel according to my needs?
If i so something like (A)objB
it is not allowed. Then i tried this:
UserControl control = objB as UserControl;
A objA = control as A;
But problem in this case is objA is null.
To avoid confusion: class A and assembly is provided by 3rd party.
Thanks in advance :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
考虑到您的层次结构,您将必须编写一个转换运算符。一般来说,没有内置的方法可以做到这一点(想想
Dog : Animal
和Cat : Animal
):您还可以使用通用反射框架并执行类似的
操作那么你可以说
这会将
b
之间的所有公共属性复制到a
。Given your hierarchy, you will have to write a conversion operator. There is no built-in way to do this in general (think
Dog : Animal
andCat : Animal
):You could also use a generic reflection framework and do something like
so then you could say
which would copy all the common properties between
b
toa
.为了使
B
可转换为A
,B
必须继承A
。即使B
包含A
的所有属性,它仍然不是A
。For
B
to be castable to aA
,B
must inheritsA
. Even ifB
contains all properties ofA
, it's still not aA
.您可以使用适配器模式
参见此处
you may use an Adapter pattern
See Here
如果 B 无法转换为 A(如
B is A
)如果不从 A 继承,就不可能实现您想要做的事情。不幸的是,C# 不支持 鸭子类型 与许多动态语言(即 Ruby)不同。
If B cannot be cast to A (as in
B is A
)it is not possible to achieve what you are trying to do without inheriting from A. Unfortunately C# doesn't support duck typing unlike many dynamic languages (i.e. Ruby).
您可以从类 A 继承:
如果您需要重写某些方法/属性,只需将它们设置为类 A 中的
virtual
即可。You can inherit from class A:
And if you need to overrride some methods/properties just set them to
virtual
in class A.我认为你实际上做不到。
为什么不将您的属性添加到部分 A 类中?
I think you actually cannot do it.
Why not adding your properties to a partial class A?