2016-12-21 5 views
3

すべての値をコンストラクタのSuperClassからSubclassに転送しようとしています。 私の考えは、スーパークラスオブジェクトをコンストラクタに渡す予定で、現在のオブジェクト(サブクラス)に値を自動的に設定します。AutoMapperを使用してSuperClassからSubClassにデータをコピーする

私はラインである「これは=」で取得していますエラー:

Cannot assign to 'this' because it is read-only 

マイビューモデルクラス

public class ItemDetailViewModel : Models.AssetItem 
    { 
     public ItemDetailViewModel() 
     { 
     } 
     public ItemDetailViewModel(Models.AssetItem model) 
     { 
      var config = new MapperConfiguration(cfg => cfg.CreateMap<Models.AssetItem, ItemDetailViewModel>()); 

      var mapper = config.CreateMapper(); 

      var a = mapper.Map<ItemDetailViewModel>(model); 

      this = a; 
     } 

     // Other Properties & Methods for View Models 

    } 

がどのように私はサブクラスにスーパークラスからデータをコピーすることができますか?

あるオブジェクトから別のオブジェクトに(同じ名前の)プロパティをコピーする方が良いでしょうか?

+0

SubClassを* SubClass内のSuperClass *で上書きしようとしていますか?論理的に見えません。あなたは外部から一方を他方にマップします。 – Darren

+0

はい、そうです。だから、そのコードをSuperClassに移すべきですか?例えばViewModelを返すAssetItem.ConvertToItemDetailViewModel() – TTCG

答えて

1

あなたが望むと思うのは、コピーコンストラクタを持つようにスーパー(親)クラスを変更することです。 Article on MSDNは、このビットを説明し、構築時に基底クラスのメソッドを呼び出すことについて第二の記事もgood example for youがありますが、ここではあなたの例に、何をしたいことは、以下の「のような」ものです:

// Used a shortened version of the name for the example here 
public class AssetItem 
{ 
    public AssetItem(AssetItem other) 
    { 
     // COPY the contents of other to your "this" instance one element at a time. 
     // Don't try assigning over "this" 
    } 
} 

public class ItemDetailViewModel : Models.AssetItem 
{ 
    public ItemDetailViewModel() 
    { 
    } 

    public ItemDetailViewModel(Models.AssetItem model) 
     : base(model) 
    { 
     // Your superclass is "set up" already by now 
    } 

     // Other Properties & Methods for View Models 

} 

読みます2つの例を通して、それが役立つかどうかを確認してください。あなたがスーパークラスのコントロールを持っていなければ、それはより困難です。それはすでにコピーコンストラクタを持っているかもしれませんが、あなたはそれを探す必要があります。

関連する問題