0

我的代码:

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????
4

4 回答 4

1

与 Silverlight 无关。

这就是强制转换所做的——你仍然返回一个对 的引用c,它一个Base.Contact.

你不能打电话ContactTypePersoncb(除非你向上,你不应该)。

那有什么问题?

于 2010-04-13T19:19:35.510 回答
1

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

于 2010-04-13T19:43:08.337 回答
0

将复制构造函数添加到基类(例如public Contact(Contact other))中,然后您可以这样做:

Contact c = new Contact();
Base.Contact cb = new Base.Contact(c);
于 2010-04-13T20:18:58.797 回答
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
于 2010-04-13T20:26:06.117 回答