c# - How to get rid of properties not belonging to the class? -


say have these 2 classes

class car {   public string carname {get;set;} }  class employeecar:car {   public string employeename {get;set;} } 

when call api

[httpget] public car getcar(employee employee) {   return getemployeecar(employee); } 

assuming

private employeecar getempoyeecar(employee employee) {      return new employeecar { carname: "car 1", employeename: "employee 1" }; } 

i getting this

{ carname: "car 1", employeename: "employee 1" } 

note employeename not belong car.

how can api return properties of car? (which return type of api) ie.

{ carname: 'car 1' } 

solution

this longer hoped (not sure if there shorter version) hope can someone

public car getcar(employee employee) {     car cardirty = getemployeecar(employee); // { carname: "car 1", employeename: "employee 1" }      car carclean = sweepforeignproperties(cardirty); // keep properties of car      return carclean; // { carname: "car 1" } }  /// <summary>only keep t's own properties, getting rid of unknown/foreign properties may have come child class</summary> public static t sweepforeignproperties<t>(t dirty) t: new() {     t clean = new t();     foreach (var prop in clean.gettype().getproperties())     {         if (prop.canwrite)             prop.setvalue(clean, dirty.gettype().getproperty(prop.name).getvalue(dirty), null);     }     return clean; } 

if using newtonsoft json, can add jsonignore attribute causes marked property being serialized/deserialized


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -