简体   繁体   中英

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.

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)

You may define a custom contract resolver which would filter out all DerivedClass properties:

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

You could provide your BaseClass with a constructor that takes a BaseClass as parameter und takes necessary information. 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 ). But i fear configuration will be complex for your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM