簡體   English   中英

我需要獲取特定對象屬性的值,但不知道 object 的類型

[英]I need to get a value of specific object's property, but don't know the type of the object

我有一個 c# object 我不知道這個 object 的類型。 (即 object o)我所知道的是,這個 object 有一個名為“ID”的 int 類型的成員。

我想獲得這個屬性的價值,但我的反射還不夠好......

我可以得到這個 object 的類型和成員:

Type type = obj.GetType();
System.Reflection.MemberInfo[] member = type.GetMember("ID");

...但不知道下一步該怎么做:-)

提前感謝馬里烏斯的幫助

您可以使用:

Type type = obj.GetType();
PropertyInfo property = type.GetProperty("ID");
int id = (int) property.GetValue(obj, null);
  • 使用PropertyInfo因為您知道它是一個屬性,這使事情變得更容易
  • 調用GetValue獲取值,傳入obj作為屬性的目標, null用於索引器 arguments(因為它是屬性,而不是索引)
  • 將結果轉換為int ,因為您已經知道它將是一個int

Jared 關於使用dynamic的建議也很好,如果您使用的是 C# 4 和 .NET 4,盡管為了避免使用所有括號,我可能會將其寫為:

dynamic d = obj;
int id = d.ID;

(除非您出於某種原因需要在單個表達式中使用它)。

這是公共財產嗎? 是這樣的話,最簡單的路線是使用dynamic

int value = ((dynamic)obj).ID;

你能用 C# 4 嗎? 在這種情況下,您可以使用dynamic

dynamic dyn = obj;
int id = dyn.ID;
public class TestClass
{
    public TestClass()
    {
        // defaults
        this.IdField = 1;
        this.IdProperty = 2;
    }

    public int IdField;
    public int IdProperty { get; set; }
}

// here is an object obj and you don't know which its underlying type
object obj = new TestClass();
var idProperty = obj.GetType().GetProperty("IdProperty");
if (idProperty != null)
{
    // retrieve it and then parse to int using int.TryParse()
    var intValue = idProperty.GetValue(obj, null);
}

var idField = obj.GetType().GetField("IdField");
if (idField != null)
{
    // retrieve it and then parse to int using int.TryParse()
    var intValue = idField.GetValue(obj);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM