如何摆脱不属于该类的属性?

时间:2017-08-18 07:20:08

标签: c# inheritance properties

说我有这两个班级

class Car {
  public string CarName {get;set;}
}

class EmployeeCar:Car {
  public string EmployeeName {get;set;}
}

当我调用此API时

[HttpGet]
public Car GetCar(Employee employee) {
  return GetEmployeeCar(employee);
}

假设

private EmployeeCar GetEmpoyeeCar(Employee employee) { 
    return new EmployeeCar { CarName: "Car 1", EmployeeName: "Employee 1" };
}

我收到了这个

{ CarName: "Car 1", EmployeeName: "Employee 1" }

请注意,EmployeeName不属于Car

如何让API仅返回Car的属性? (这是API的返回类型)即。

{ CarName: 'Car 1' }

这比我希望的要长得多(不确定是否有更短的版本)但我希望这可以帮助某人

public Car GetCar(Employee employee) {
    Car carDirty = GetEmployeeCar(employee); // { CarName: "Car 1", EmployeeName: "Employee 1" }

    Car carClean = SweepForeignProperties(carDirty); // Only keep properties of Car

    return carClean; // { CarName: "Car 1" }
}

/// <summary>Only keep T's own properties, getting rid of unknown/foreign properties that may have come from a child class</summary>
public static T SweepForeignProperties<T>(T dirty) where 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;
}

1 个答案:

答案 0 :(得分:0)

如果您使用的是Newtonsoft Json,则可以添加JsonIgnore属性,该属性会导致标记属性被序列化/反序列化