は私がこのクラスに属さないプロパティを取り除くにはどうすればいいですか?
{ CarName: "Car 1", EmployeeName: "Employee 1" }
注股関節を取得しています
private EmployeeCar GetEmpoyeeCar(Employee employee) {
return new EmployeeCar { CarName: "Car 1", EmployeeName: "Employee 1" };
}
を想定し
[HttpGet]
public Car GetCar(Employee employee) {
return GetEmployeeCar(employee);
}
このAPIを呼び出すと、私はこれらの2クラス
class Car {
public string CarName {get;set;}
}
class EmployeeCar:Car {
public string EmployeeName {get;set;}
}
を持っていると言いますt EmployeeName
はCar
に属しません。
Car
のプロパティのみを返すようにAPIを取得するにはどうすればよいですか? (これはAPIの戻り値の型です)。
{ CarName: 'Car 1' }
SOLUTION
これは、はるかに長く、私が望んだ以上ですが、私はあなたがNewtonsoftを使用している場合、これは誰か
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;
}
[see this this](https:// stackoverflow .com/a/1875702) –
質問が単純なC#継承以上のものに関係する場合は、より多くのコンテキストを提供する必要があります。マークされた重複は、前者に対処します(そして、「何?あなたは狂っていますか?」)。これがより合理的であると思われるシリアライゼーションシナリオがある場合は、より具体的な新しい質問を投稿し、これを使用する理由と方法についてさらに詳しく説明する必要があります。 –
@PeterDuniho and Nobodyありがとうございましたが、それは私がグーグルで見つけた最初の結果の1つでした。明らかにあなたたちは私の質問を読んでいない、タイトルだけ。私のタイトルが間違っているかもしれない、それを編集させてください。それはそれをより明確にするか? – Aximili