我有以下课程。我想不希望派生类序列化“名称”,但是,以下代码似乎不起作用。如果我声明派生类的实例,“Name”属性仍然会被序列化..
[DataContract]
public class Base
{
[DataMember]
public virtual string Name
{get; set; }
}
[DataContract]
public class Derived: Base
{
[IgnoreDataMember]
public override string Name
{get; set; }
}
答案 0 :(得分:0)
如果在Base类中声明属性virtual会怎么样?然后在派生类
中覆盖它答案 1 :(得分:0)
尝试使用ScriptIgnore
(json)或XmlIgnore
(xml)属性,具体取决于您要序列化的内容。这应该可以防止该成员被序列化。
答案 2 :(得分:0)
如果您想尝试使用XmlSerializer,请输入代码
public class Base
{
[XmlIgnore]
public virtual string Name { get; set; }
}
public class Derived : Base
{
[XmlIgnore] //Remove this to include
public override string Name { get; set; }
}
MemoryStream memStream = new MemoryStream();
XmlSerializer xmlSer = new XmlSerializer(typeof(Derived));
xmlSer.Serialize(memStream, new Derived() { Name = "aaaa" });
MessageBox.Show(Encoding.UTF8.GetString(memStream.ToArray()));