从类中动态获取属性值

时间:2013-03-28 21:04:01

标签: c# winforms

我有一个我想从中动态检索属性的类

这是来自班级的样本

namespace TEST
{
    public class Data
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

我正在尝试使用GetProperty,但它总是返回null

static object PropertyGet(object p, string propName)
{
    Type t = p.GetType();
    PropertyInfo info = t.GetProperty(propName);
    if (info == null)
        return null;
    return info.GetValue(propName);
}
像这样

    var data = new Data();

    var x = PropertyGet(data, "Username");
    Console.Write(x?? "NULL");

2 个答案:

答案 0 :(得分:2)

这一行是错的,应该为你抛出一个例外:

return info.GetValue(propName);

您需要传入要从中提取属性的对象,即

return info.GetValue(p);

另请注意,目前data.Username 为空。你想要这样的东西:

var data = new Data { Username = "Fred" };

我已经通过这两项更改验证了它的确有效。

答案 1 :(得分:1)

这有效:

public class Data
{
    public string Username { get; set; }
    public string Password { get; set; }
}

public class Program
{
    static object PropertyGet(object p, string propName)
    {
        Type t = p.GetType();
        PropertyInfo info = t.GetProperty(propName);

        if (info == null)
        {
            return null;
        }
        else
        {
            return info.GetValue(p, null);
        }
    }

    static void Main(string[] args)
    {
        var data = new Data() { Username = "Fred" };

        var x = PropertyGet(data, "Username");
        Console.Write(x ?? "NULL");
    }
}