简体   繁体   English

根据其名称字符串调用Property

[英]Call Property based on a string of its name

I need to call a public property of a class based on the string value of its name, as I won't know until run time what properties are required. 我需要根据其名称的字符串值调用类的公共属性,因为在运行时我不知道需要什么属性。 I'm trying to use reflections unsuccessfully. 我试图使用反射失败。 The class looks like this: 这个类看起来像这样:

class FieldCalculation
{
    public string MyValue
    {
        get
        {
            return "Test Data";
        }
    }
}

I think access the value of the property should look something like this: 我认为访问属性的值应该如下所示:

FieldCalculation myClass = new FieldCalculation();
string value = myClass.GetType().GetProperty("MyValue");

Any help would be appreciated. 任何帮助,将不胜感激。

You nearly had it. 你几乎拥有它。 What you were doing was getting the property definition . 你正在做的是获得属性定义 You need to ask that property to get you the value, and you pass it the instance. 您需要询问该属性以获取值,然后将实例传递给它。 This is the working code: 这是工作代码:

FieldCalculation myClass = new FieldCalculation();
string value = (string)myClass.GetType().GetProperty("MyValue").GetValue(myClass);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM