开发者

how to input a string and get the same name property from a object? [duplicate]

开发者 https://www.devze.com 2023-04-06 10:57 出处:网络
This quest开发者_JAVA技巧ion already has answers here: Closed 11 years ago. Possible Duplicate: Get property value from string using reflection in C#
This quest开发者_JAVA技巧ion already has answers here: Closed 11 years ago.

Possible Duplicate:

Get property value from string using reflection in C#

say, classA has properties A,B,C,D,E.. I wanna build a method StringToProperty so that StringToProperty("A") returns A.

I guess it can be done by reflection, but i have no knowledge of it now. Any simple examples?

THx, i will close it, plz vote to close


var type = classA.GetType();
PropertyInfo property = type.GetProperty("A");
var propertyValue = property.GetValue(anInstance, null);


Are you writing the method in the class that has the properties? If so just do the following:

public object StringToProperty(string prop)
{
    switch(prop)
    {
        case "A":
           return a;
        case "B":
           return b;

    }
}

Or you can just use reflection if not:

Type type = classA.GetType();
return type.GetProperty(propertyString).GetValue(classAInstance, null);


If you do a very simple Google search you can find lots written about this!

Here's the first article I found that talks about exactly what you need.

And you could very easily write:

public object StringToProperty(string propertyName)
{
   Type type = ClassA.GetType();
   PropertyInfo theProperty = type.GetProperty(propertyName);

   object propertyValue = theProperty.GetValue(yourClassAInstance, null);
   return propertyValue;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消