2016-03-20 24 views
1

誰でも派生クラスオブジェクトの値を取得する方法をお手伝いできますか?c#asp mvc派生クラスのオブジェクト値を取得する方法

派生クラス(通貨)から親クラス(エンティティ)にキャストしようとすると、nullが返されます。 DBから 実数値:http://prntscr.com/ahmy9h ヌルのエンティティを鋳造後:http://prntscr.com/ahmxxo

public class Entity 
{ 
    public System.Guid Id { get; set; } 
    public string Name { get; set; } 
} 

public class Currency:Entity 
{ 
    public Currency() 
    { 
     this.BankServices = new HashSet<BankService>(); 
    } 

    public new System.Guid Id { get; set; } 
    public new string Name { get; set; } 

    public virtual ICollection<BankService> BankServices { get; set; } 
} 

public virtual IEnumerable<Entity> GetItems() 
{ 
    // check the cache 
    Dictionary<Guid, Entity> EntityData = GetCachedData(); 

    // If it's not in the cache, read it from the repository 
    if (EntityData == null) 
    { 
     // Get the data 
     Dictionary<Guid, Entity> EntityDataToCache = new Dictionary<Guid, Entity>(); 

     // get data from the repository 
     IEnumerable<Entity> entityDataFromDb = LoadData(); 
     foreach (var item in entityDataFromDb) 
     { 
      var itemValue = item; // ALL ZEROS http://prntscr.com/ahmxxo 
      var itemValue2 = (Currency)item; // REAL VALUES http://prntscr.com/ahmy9h 
      EntityDataToCache[(Guid)item.GetType().GetProperty("Id").GetValue(item, null)] = item; 
     } 

     if (EntityDataToCache.Any()) 
     { 
      // Put this data into the cache for 30 minutes 
      Cache.Set(CacheKey, EntityDataToCache, 30); 
     } 
    } 

    var cache = Cache.Get(CacheKey); 

    var result = cache as Dictionary<Guid, Entity>; 
    return result.Values; 
} 
+0

["new"修飾子の重複は、ベースの実装でNULLプロパティ値を持つ可能性があります](http://stackoverflow.com/questions/6239790/new-modifier-causes-base-implementations-to-have-null-property - 値) – cokeman19

答えて

1

私はthisまたは継承と隠ぺいの違いをブラッシュアップに類似したものを読んでお勧めします。あなたの場合、Currency.IdCurrency.Nameプロパティのnew修飾子は、親クラスのプロパティを非表示にするようにコンパイラに指示します。したがって、Currencyインスタンスでこれらのプロパティを割り当てると、その値はそのインスタンスにCurrencyのインスタンスとしてのみ適用されます。あなたのコードから見たように、そのインスタンスをEntityのインスタンスにキャストすると、それらのプロパティへの参照は、Entityプロパティ(設定していない)への参照になります。あなたが探していると思われる動作を得るには、Entityのプロパティ宣言にvirtual修飾子を追加し、次にnewoverrideに変更してCurrencyに変更します。もちろん、これらのプロパティの動作をCurrencyEntityの間で変更しない場合は、Currencyでそれらをオーバーライドする必要はありません。Entityを継承するすべてのクラスで利用できるようになります。希望が役立ちます。

+0

ジョン、迅速な対応に感謝します。出来た – Alexandr

関連する問題