试图将字符串转换为值

sin*_*ngh -3 c#

我上课了

class Names{
    public static string One = "Value of One";
};
Run Code Online (Sandbox Code Playgroud)

我有一个方法

void GetValue(string strValue)
{
    string strDef = "Names." + strValue;
    //Now here i want to get the value of Names.One if the value of strValue is "One"
    //I want to get the value of Names.One in a variable
    strResult = ??;//what to do here
    //so that the contents of strResult will be "Value of One"
}
Run Code Online (Sandbox Code Playgroud)

我这样叫GetValue

GetValue("One");
Run Code Online (Sandbox Code Playgroud)

我不想使用if else或字典.我想知道是否有可能以这种方式做到这一点?

我试过像这样的反射,但它总是返回null我也在类中有一个静态属性,所以我不创建一个对象

 PropertyInfo pinfo = typeof(Names).GetProperty("One");
 object value = pinfo.GetValue(null, null);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Øyv*_*hen 9

您可以使用反射执行此操作,但我建议您将Names类更改为Dictionary.

然后,你可以添加元素到Dictionary这样

names.Add("One", "Value of one");
Run Code Online (Sandbox Code Playgroud)

然后你的GetValue方法将非常简单

void GetValue(string strValue)
{
  if( names.ContainsKey(strValue))
  {
    return names[strValue];
  }
  return "Not found";
}
Run Code Online (Sandbox Code Playgroud)