[英]How do you get the Value of a property from PropertyInfo?
我有一個具有一組屬性的對象。 當我獲得特定實體時,我可以看到我正在尋找的字段 ( opportunityid
),並且它的Value
屬性是這個機會的Guid
。 這是我想要的值,但它並不總是用於機會,因此我不能總是查看opportunityid
,因此我需要根據用戶提供的輸入來獲取該字段。
到目前為止,我的代碼是:
Guid attrGuid = new Guid();
BusinessEntityCollection members = CrmWebService.RetrieveMultiple(query);
if (members.BusinessEntities.Length > 0)
{
try
{
dynamic attr = members.BusinessEntities[0];
//Get collection of opportunity properties
System.Reflection.PropertyInfo[] Props = attr.GetType().GetProperties();
System.Reflection.PropertyInfo info = Props.FirstOrDefault(x => x.Name == GuidAttributeName);
attrGuid = info.PropertyType.GUID; //doesn't work.
}
catch (Exception ex)
{
throw new Exception("An error occurred when retrieving the value for " + attributeName + ". Error: " + ex.Message);
}
}
動態attr
包含我正在尋找的字段(在本例中是opportunityid
),該字段又包含一個值字段,它是正確的Guid
。 但是,當我獲得PropertyInfo
信息( opportunityid
)時,它不再具有Value
屬性。 我嘗試查看PropertyType.GUID
但這沒有返回正確的Guid
。 我怎樣才能得到這個屬性的價值?
除非屬性是static
的,否則僅通過PropertyInfo
對象來獲取屬性的值是不夠的。 當您編寫“普通” C# 並且需要獲取某個屬性的值時,例如MyProperty
,您可以這樣寫:
var val = obj.MyProperty;
您提供兩件事——屬性名稱(即獲取什么)和對象(即從何處獲取)。
PropertyInfo
代表“什么”。 您需要單獨指定“從哪里”。 你打電話時
var val = info.GetValue(obj);
您將“從哪里”傳遞給PropertyInfo
,讓它為您從對象中提取屬性的值。
注意:在 .NET 4.5 之前,您需要將 null 作為第二個參數傳遞:
var val = info.GetValue(obj, null);
如果屬性名稱發生變化,您應該使用GetValue
:
info.GetValue(attr, null);
該方法的最后一個屬性可以是null
,因為它是索引值,並且僅在訪問數組時才需要,例如Value[1,2]
。
如果您事先知道屬性的名稱,則可以使用它的dynamic
行為:您可以調用屬性而無需自己進行反射:
var x = attr.Guid;
使用PropertyInfo.GetValue()
。 假設您的屬性具有Guid?
那么這應該工作:
attrGuid = ((System.Guid?)info.GetValue(attr, null)).Value;
請注意,如果屬性值為 null,則會引發異常。
嘗試:
attrGuid = (Guid)info.GetValue(attr,null)
只是要補充一點,這可以通過反射來實現(即使對於未實例化的嵌套類/類型中的屬性)
Imports System
Imports System.Reflection
Public Class Program
Public Shared Sub Main()
Dim p = New Person()
For Each nestedtype in p.Gettype().GetNestedTypes()
For Each prop in nestedtype.GetProperties(BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Static)
Console.WriteLine(nestedtype.Name & " => " & prop.Name)
Next
Next
End Sub
End Class
Public Class Person
Public Property Name As String
Public Property AddressDetail As Address
Public Class Address
Public Property Street As String
Public Property CountryDetail As Country
End Class
Public Class Country
Public Property CountryName As String
End Class
End Class
打印以下內容:
地址 => 街道
地址 => 國家詳情
國家 => 國家名稱
小提琴: https ://dotnetfiddle.net/6OsRkp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.