[英]C# Get object inside of object that is a generic
我有幾個包含地址對象的視圖模型。 該地址對象當然有address1,address2,city,state和zip。
我們正在使用郵政編碼地址驗證系統,我希望我的所有開發人員能夠調用一個幫助程序類,它將為地址對象嗅探View Model對象。 如果找不到它,它將檢查視圖模型是否具有基本的address1,address2和etc屬性......在任何一種情況下我都需要它來獲取屬性對象地址的地址信息或獲取地址屬性...
所以我的助手類方法簽名如下所示:
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;
}
}
這適用於View Model的一部分地址屬性。 現在我磕磕絆絆的是檢測View Model是否有這樣的屬性:
public EntityAddressVM Address { get; set; }
我需要從泛型中獲取該對象,然后獲取其地址屬性。 我已經找到了這個對象,但之后我就被卡住了......
bool hasEntityAddress = objType.GetProperties().Any(p => p.PropertyType == typeof(EntityAddressVM));
我需要幫助的是:
確定傳入的viewModel(mvc)是否具有地址對象或具有地址屬性。
如果它確實有地址對象,則獲取地址屬性,否則從ViewModel獲取地址屬性。
我用一個很好的擴展方法來查看對象屬性:
/// <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
則從模型中獲取Address屬性。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.