[英]How to get only base class properties from derived class?
My code is like this 我的代码是这样的
public class BaseClass
{
public string Field1 { get; set; }
}
public class DerivedClass: BaseClass
{
public string Field2 { get; set; }
}
var obj = new DerivedClass { Field1 = "aaa", Field2 = "bbb" };
I have to serialize obj
but I only need the BaseClass
properties since DerivedClass
properties are "additional info" which is added after deserialization. 我必须序列化obj
但我只需要BaseClass
属性,因为DerivedClass
属性是反序列化后添加的“附加信息”。
How can I get them? 我怎么能得到它们? (I can't use [JSonIgnore]
decorator because I have to send DerivedClass
objects over websocket and I'll lose informations) (我不能使用[JSonIgnore]
装饰器,因为我必须通过websocket发送DerivedClass
对象,我将丢失信息)
You may define a custom contract resolver which would filter out all DerivedClass
properties: 您可以定义一个自定义合约解析程序,它将过滤掉所有DerivedClass
属性:
public class NoDerivedContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
property.ShouldSerialize = _ => property.DeclaringType != typeof(DerivedClass);
return property;
}
}
// .................
var obj = new DerivedClass { Field1 = "aaa", Field2 = "bbb" };
var json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings {
ContractResolver = new NoDerivedContractResolver()
});
Console.WriteLine(json);
// Output:
// {"Field1":"aaa"}
Demo: https://dotnetfiddle.net/Qailvp 演示: https : //dotnetfiddle.net/Qailvp
You could provide your BaseClass
with a constructor that takes a BaseClass
as parameter und takes necessary information. 您可以为BaseClass
提供一个构造函数,该构造函数将BaseClass
作为参数并获取必要的信息。 This way you could create a new object and serialize it: 这样您就可以创建一个新对象并将其序列化:
public class BaseClass
{
public string Field1 { get; set; }
public BaseClass(){ }
public BaseClass(BaseClass dc)
{
this.Field1 = dc.Field1;
}
}
public class DerivedClass : BaseClass
{
public string Field2 { get; set; }
}
Calling it like this: 这样称呼它:
var obj = new DerivedClass { Field1 = "aaa", Field2 = "bbb" };
BaseClass obj_base = new BaseClass(obj);
Can't you map a third class that contain all the data to serialise like this: 你不能映射包含所有数据序列化的第三个类,如下所示:
public class BaseClass
{
public string Field1 { get; set; }
}
public class DerivedClass: BaseClass
{
public string Field2 { get; set; }
}
public class BaseClassDTO{
public string Field1 { get; set; }
public BaseClassDTO(BaseClass baseClass){
this.Field1 = baseClass.Field1;
}
}
Some have propose ( https://github.com/quozd/awesome-dotnet#object-to-object-mapping ). 有人建议( https://github.com/quozd/awesome-dotnet#object-to-object-mapping )。 But i fear configuration will be complex for your need. 但我担心配置会因您的需要而变得复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.