【发布时间】:2018-01-26 19:00:23
【问题描述】:
假设我有这两个类
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;
}
【问题讨论】:
-
有一个look at this
-
如果您的问题不仅仅涉及简单的 C# 继承,您需要提供更多上下文。标记的重复地址是前者(归结为“什么?你疯了吗?”)。如果您有一个序列化场景,您认为这样做更合理,您需要发布一个更具体的新问题,并提供更多关于您打算使用它的原因和方式的详细信息。
-
@PeterDuniho 和没人谢谢,但这是我在谷歌上找到的第一个结果之一。显然你们没有阅读我的问题,只阅读了标题。可能是我的标题错了,让我编辑一下。是不是更清楚了?
-
“是不是更清楚了?”——不,一点也没有。问题的很大一部分是您的问题没有提供minimal reproducible example 来显示问题所在,也没有对您尝试解决的问题进行任何解释。如果您希望 API 返回仅具有
CarName属性的对象,则不要返回也具有EmployeeName属性的对象。例如,将您确实想要的数据复制到您想要想要的类型的新对象中。试图从对象中删除属性是徒劳的。说他们不“属于”班级,而他们显然属于班级,这简直令人困惑。
标签: c# inheritance properties