2017-08-18 8 views
-1

は私がこのクラスに属さないプロパティを取り除くにはどうすればいいですか?

{ 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 EmployeeNameCarに属しません。

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; 
} 
+0

[see this this](https:// stackoverflow .com/a/1875702) –

+0

質問が単純なC#継承以上のものに関係する場合は、より多くのコンテキストを提供する必要があります。マークされた重複は、前者に対処します(そして、「何?あなたは狂っていますか?」)。これがより合理的であると思われるシリアライゼーションシナリオがある場合は、より具体的な新しい質問を投稿し、これを使用する理由と方法についてさらに詳しく説明する必要があります。 –

+0

@PeterDuniho and Nobodyありがとうございましたが、それは私がグーグルで見つけた最初の結果の1つでした。明らかにあなたたちは私の質問を読んでいない、タイトルだけ。私のタイトルが間違っているかもしれない、それを編集させてください。それはそれをより明確にするか? – Aximili

答えて

0

役立つことを願って(そこに短いバージョンがあるかどうかわかりません) Json、JsonIgnore属性を追加すると、マークされたプロパティが直列化/逆シリアル化されなくなります。

+0

ありがとうAcidJunkie。それは場合によってはうまくいくかもしれませんが、私はEmployeeCarプロパティを別の場所でシリアライズ可能にする必要があります。私は解決策を見つけた:) – Aximili

関連する問題