最新更新請訪問: http://denghejun.github.io
C#中匿名對象的一般寫法是這樣的:
object o=new {Name="TestName"};
有時候我們會嘗試從這個匿名對象中獲取值,在使用中發現例如已知類型的對象如T model,
下面的代碼是沒有問題的:
object value = null;
Type objType = typeof(T);
var propertInfo = objType.GetProperty(propertyName);
if (propertInfo != null)
{
value = propertInfo.GetValue(model, null);
}
但是對於匿名對象,該代碼失效,原因就在於匿名對象沒有自己具體的類型,所有typeof取到
的類型里將會找不到該屬性(Name),因為無法獲取他的值。更為普遍的兼容做法是使用實例
的GetType()方法:
object value = null;
Type objType = model.GetType();
var propertInfo = objType.GetProperty(propertyName);
if (propertInfo != null)
{
value = propertInfo.GetValue(model, null);
}
這樣,不管是匿名對象還是自定義(已知類型)對象的屬性值都可以獲取到了。