Casting classes
I have 2 classes:
public class ClassA
public class ClassB (from another namespace) : ClassA
I use开发者_运维技巧 method at ClassA
public static ClassA Deserialize(string path)
{
ClassA classA;
//classA=code...
return classA;
}
I invoke this method at classB
public void DoSomething()
{
ClassB classB=(ClassB)ClassA.Deserialize("c:\directory\file.xml);
}
method deserialize works, but i get error that cannont cast ClassA to ClassB.
How to deal with this?
public static ClassA DeserializeFromXml(string path)
{
XmlSerializer s = new XmlSerializer(typeof(ClassA));
ClaasA h;
TextReader r = new StreamReader(path);
h = (ClassA)s.Deserialize(r);
r.Close();
return h;
}
Maybe something with deserialize(string path, Type objectType ) ??
I could can change method Deserialize if it would necessary
A isn't a B. B is an A
(ClassB) something_that_is_A cannot be done unless it is a B or a derivative of it.
Without showing your Deserialize
code it's pretty hard to say what's going on. This is likely to be the heart of the problem - you need to make Deserialize
actually create an instance of ClassB
(or a derived class) if you want to be able to cast the result to ClassB
. If your Deserialize
method creates an instance of ClassA
and then sets a bunch of properties, you'll need to either change it or find another way of creating a ClassB
instance later.
You can only an expression cast to ClassB
if the value is a reference to an actual instance of ClassB
. If the object is only an instance of ClassA
then you won't be able to cast - what would you expect to happen to any extra fields etc in ClassB
? Unless a user-defined conversion, casting for a reference type only performs a reference conversion - it doesn't create a new object. (See Eric Lippert's blog post on representation and identity for more details.)
Your method returns a void, therefore you trying to cast the return of void to be ClassB.
Having ClassB
inherit from ClassA
does not allow a ClassA
object to be cast into a ClassB
object, as all ClassA objects are not inevitably ClassB
objects.
If you want to know if your deserialized object is a ClassB object, you can use this code :
ClassA a = ClassA.Deserialize("c:\directory\file.xml");
ClassB b = a as ClassB;
If the object isn't a ClassB
instance, b will be null. Otherwise you will have your instance as a ClassB
object.
精彩评论