2010-04-13 124 views
0

我的代码:将对象投射到基类,返回extented对象?

public class Contact 
{ 
    public string id{ get; set; } 
    public string contact_type_id { get; set; } 
    public string value{ get; set; } 
    public string person_id { get; set; } 
    public Contact() 
    { 

    } 
} 

public class Contact:Base.Contact 
{ 
    public ContactType ContactType { get; set; } 
    public Person Person {get; set;} 
    public Contact() 
    { 
     ContactType = new ContactType(); 
     Person = new Person(); 
    } 
} 

和:

Contact c = new Contact(); 
Base.Contact cb = (Base.Contact)c; 

问题:

The **cb** is set to **Contac** and not to **Base.Contact**. 
Have any trick to do that???? 

回答

0

我读的答案,还是不明白的问题! 上述代码有什么问题?


此外,从评论中,我明白你只需要序列化基类。首先,我认为没有问题。看看例子 -

class A 
{ 
    public int a = -1; 
}; 

class B : A 
{ 
    public int b = 0; 
}; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     A aobj = new B(); 
     aobj.a = 100; // <--- your aobj obviously cannot access B's members. 
     Console.In.ReadLine(); 
    } 
} 

现在,如果你必须使你的序列化函数为虚拟的,那么是的,有问题。那么这可能会有所帮助 -

abstract class Ia 
{ 
    public abstract void Serialize(); 
} 
class A : Ia 
{ 
    public int a = -1; 
    sealed public override void Serialize() { 
     Console.Out.WriteLine("In A serialize"); 
    } 
}; 

class B : A 
{ 
    public int b = 0; 
    /* 
    * Error here - 
    public override void Serialize() 
    { 
     Console.Out.WriteLine("In B serialize"); 
    } 
    */ 

    //this is ok. This can only be invoked by B's objects. 
    public new void Serialize() 
    { 
     Console.Out.WriteLine("In B serialize"); 
    } 
}; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     A aobj = new B(); 
     aobj.Serialize(); 
     Console.In.ReadLine(); 
    } 
} 

//Output: In A serialize 
1

无关使用Silverlight。

这是什么铸造 - 你仍然返回参考c,其中 a Base.Contact

你不能拨打ContactTypePersoncb(除非你upcast,你不应该)。

这是什么问题?

+0

我只需要实现我的基类,这是我的问题! – JoeLoco 2010-04-13 19:22:58

+0

DataContractJsonSerializer做了深度serealizer,但我只需要Base.Contact的特性。 – JoeLoco 2010-04-13 19:24:47

+0

我需要一个DownCast,但是当我将Cast对象向下投射我的cb时! – JoeLoco 2010-04-13 19:28:13

1

你绝对不能通过强制转换将类转换为其基类之一。根据您使用的序列化类型,您可能会告诉序列化程序假定该类是基本类型,这会限制基本类型成员的序列化。

0

添加一个拷贝构造函数为基类(例如public Contact(Contact other)),然后你可以这样做:

Contact c = new Contact(); 
Base.Contact cb = new Base.Contact(c);