问题描述
我遇到了一个问题,我想将不同类型的对象向下转换为派生层次结构中更长的对象,我认为最好的方法只是显示一些简单的代码:
Hi people, I''ve ran into a problem where i wanna downcast a object of a different type to a object longer down in a derived hierarchy, i think the best way is just to show some simple code:
class mammal {}
class dog : mammal{}
class cat : : mammal{}
class program
{
public main()
{
mamal m = new mamal();
cat c = new cat();
c = (cat)m; //this give me an invalid cast exception!
c = (m as cat); //same exception as above
}
}
就像我想给猫对象一个哺乳动物对象/将哺乳动物中的所有信息放到猫对象中(这是从哺乳动物派生的)一样,我尝试了隐式运算符,但发现在派生类中这样做是无效的.因此,有没有一种方法可以手动完成所有操作?
谢谢-Jackie
as seen i wanna give a cat object a mammal object/have all the info in the mammal putted into the cat object, which is derived from mammal, i tried implicit operators but saw that this is invalid to do in derived classes. so is there a way to do this without doing everything manually?
thanks - Jackie
推荐答案
public static Namespace1.SomeClass Convert(Namespace2.SomeClass someClass) {
Namespace1.SomeClass rtn = new Namespace1.SomeClass();
rtn.SomeProp = someClass.SomeProp;
rtn.SomeOtherProp = someClass.SomeOtherProp;
return rtn;
}
或
您可以使用反射,也可以使一个反射自另一个反射,并使其具有相同的属性,并进行其他扩展
另外,如果您对其中一个类拥有代码,则可以检查类中显式和隐式的重载.
祝你好运,
OI
or
You can use reflection, or make one derive from another and have one with common properties and other extend that
Also, if you own the code to one of the classes, you can check into overloading explicit and implicit on your class.
Good luck,
OI
这篇关于在派生层次结构中向下投放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!