C# 将对象强制转换为基类,是否返回扩展对象?
我的代码:C# 将对象强制转换为基类,是否返回扩展对象?,c#,silverlight,casting,extends,C#,Silverlight,Casting,Extends,我的代码: 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:Ba
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();
}
}
以及:
问题是:
The **cb** is set to **Contac** and not to **Base.Contact**.
Have any trick to do that????
与Silverlight无关 这就是casting所做的——您仍然返回对
c
的引用,而是的基础。请联系
您不能在cb
上调用ContactType
或Person
(除非您向上转换,您不应该这样做)
这有什么问题吗?您肯定不能通过强制转换将一个类转换为它的基类。根据所使用的序列化类型,您可以告诉序列化程序假定类为基类型,这将限制对基类型成员的序列化。将副本构造函数添加到基类中(例如,公共联系人(联系其他人)
),然后您可以执行以下操作:
Contact c = new Contact();
Base.Contact cb = new Base.Contact(c);
我看了答案,还是不明白问题所在!
上面的代码有什么问题?
此外,从评论中,我了解到您只需要序列化基类。首先,我认为没有问题。看看这个例子-
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();
}
}
我只需要实现我的基类,这是我的问题!!DataContractJsonSerializer做了一个深层的serealizer,但我只需要Base.Contact上的属性。我需要向下投射,但当我向下投射对象时,它会向上投射我的cb!!可能最简单的方法是向Base.Contact添加一个复制构造函数,然后可以var cb=new Base.Contact(c);cb应为Base.Contact型。但这感觉有点像黑客攻击。@是的,如果你真的只想要基,你就必须按照Neal的描述重新创建它,从派生类复制值。
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