我需要获取特定对象的属性值,但不知道对象的类型

本文关键字:对象 不知道 类型 属性 获取 | 更新日期: 2023-09-27 18:05:44

我有一个c#对象,我不知道这个对象的类型。(即对象0)我所知道的是,这个对象有一个名为"ID"的int类型成员。

我想得到这个属性的值,但我对反射不够好…

可以得到这个对象的类型和成员:

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

…但不知道下一步该做什么:-)

提前感谢您的帮助科学家们

我需要获取特定对象的属性值,但不知道对象的类型

这是一个公共属性吗?那么最简单的方法就是使用dynamic

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

您可以使用:

Type type = obj.GetType();
PropertyInfo property = type.GetProperty("ID");
int id = (int) property.GetValue(obj, null);
  • 使用PropertyInfo,因为你知道它是一个属性,这使事情变得更容易
  • 调用GetValue获取值,传递obj作为属性和null的索引器参数的目标(因为它是属性,而不是索引)
  • 将结果转换为int,因为你已经知道它将是int

Jared关于使用dynamic的建议也很好,如果你正在使用c# 4和。net 4,尽管为了避免所有的括号,我可能会把它写成:

dynamic d = obj;
int id = d.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);
}