2016-04-14 122 views
2

我有幾個包含地址對象的視圖模型。那個地址對象當然有address1,address2,city,state和zip。
我們正在使用郵政編碼地址驗證系統,並且我希望我的所有開發人員都能夠調用幫助程序類,它將查看地址對象的View Model對象。如果它沒有找到它,它將檢查視圖模型是否具有基本的address1,address2等屬性......無論哪種情況,我都需要它獲取屬性對象地址的地址信息或獲取地址屬性...C#獲取通用對象的對象

所以我的助手類的方法簽名是這樣的:

public void ShowVerificationWithReflection<T>(ModelStateDictionary modelState, T viewModel) where T : AMSBaseVM 

我然後執行以下操作:

var objType = viewModel.GetType(); 
List<PropertyInfo> properties = new List<PropertyInfo>(); 

properties.AddRange(objType.GetProperties()); 

foreach (PropertyInfo property in properties) 
{ 
    if (property.CanRead) 
    { 
     if (property.Name == "Address1") testAddress.Address1 = property.GetValue(viewModel, null) as string; 
     if (property.Name == "Address2") testAddress.Address2 = property.GetValue(viewModel, null) as string; 
     if (property.Name == "City") testAddress.City = property.GetValue(viewModel, null) as string; 
     if (property.Name == "StCd") testAddress.StateCodeId = (long)property.GetValue(viewModel, null); 
     if (property.Name == "Zip") testAddress.Zip = property.GetValue(viewModel, null) as string; 
    } 
} 

這適用於地址屬性的視圖模型的一部分。 現在我所用,如果視圖模型具有這樣的屬性被檢測絆腳石:

public EntityAddressVM Address { get; set; } 

我需要從一般的那個對象,然後獲取其地址屬性。我已經能夠找到的對象,但在那之後我被卡住......

bool hasEntityAddress = objType.GetProperties().Any(p => p.PropertyType == typeof(EntityAddressVM)); 

什麼我需要幫助的是:

  1. 確定是否進入視圖模型(MVC)有地址對象或具有地址屬性。

  2. 如果它具有地址Object,則獲取地址屬性,否則從ViewModel獲取地址屬性。

+0

如何通過'SingleOrDefault'調用來交換'Any'調用,不僅僅是檢查一個屬性是否存在,而是獲取它。 – thehennyy

+0

這是非常古老的代碼100 +視圖模型等,我們不被允許深入重構。 :(不幸的是,我對泛型沒有深入的瞭解 - 儘管要加快速度,但無論哪種方式,即使使用泛型,我仍然需要獲取對象地址並解析值..我被困在那部分 –

+0

有人提到有人使用界面來簡化這個過程,在下面的答案後,我繼續遇到各種痛苦點,所以我將這些建議和下面的答案結合起來,現在一切正常。我的界面具有屬性,我所有的類和驗證碼都需要,勝利者是我能夠刪除大量重複的,複雜的代碼等。感謝指針夥計。 –

回答

2

有,我用它來看看對象的屬性一個很好的擴展方法:

/// <summary> 
///  Gets all public properties of an object and and puts them into dictionary. 
/// </summary> 
public static IDictionary<string, object> ToDictionary(this object instance) 
{ 
    if (instance == null) 
     throw new NullReferenceException(); 

    // if an object is dynamic it will convert to IDictionary<string, object> 
    var result = instance as IDictionary<string, object>; 
    if (result != null) 
     return result; 

    return instance.GetType() 
     .GetProperties() 
     .ToDictionary(x => x.Name, x => x.GetValue(instance)); 
} 

然後,你可以做這樣的事情:

var addressObject = model 
    .ToDictionary() 
    .FirstOrDefault(x => x.Value is EntityAddressVM) 
    .Value; 

如果null然後獲取地址來自模型的屬性。

希望這會有所幫助。

+0

獲取設計時間錯誤,Method'ToDictionary'有0個參數,但用2個參數調用。 –

+0

在'.cs'文件的頂部添加'using System.Linq;' –

+0

添加了linq並將代碼改爲了一點....現在測試... return instance.GetType() .GetProperties() .ToDictionary(x => x.Name,x => x.GetValue(instance,null)); –