通过其粗俗的名称获取属性值

Ari*_*ian 3 c# reflection static c#-4.0

请考虑这个课程:

public static class Age
{    
    public static readonly string F1 = "18-25";
    public static readonly string F2 = "26-35";
    public static readonly string F3 = "36-45";
    public static readonly string F4 = "46-55";
}
Run Code Online (Sandbox Code Playgroud)

我想编写一个获得"F1"并返回"18-25"的函数.例如

private string GetValue(string PropertyName)
....
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Aka*_* KC 11

您只需使用SWITCHstatement来执行上述任务:

public static string GetValue(string PropertyName)
{
    switch (PropertyName)
    {
        case "F1":
            return Age.F1;
        case "F2":
            return Age.F2;
        case "F3":
            return Age.F3;
        case "F4":
            return Age.F4;
        default:
            return string.Empty;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Reflection,你可以这样做:

public static string GetValueUsingReflection(string propertyName)
{
    var field = typeof(Age).GetField(propertyName, BindingFlags.Public | BindingFlags.Static);
    var fieldValue = field != null ? (string)field.GetValue(null) : string.Empty;
    return fieldValue;
}
Run Code Online (Sandbox Code Playgroud)


Hog*_*gan 5

我做了一些测试,对于这种情况,这将有效:

public static string GetValue(string PropertyName)
{
   return typeof(Age).GetField(PropertyName).GetValue(typeof(Age));
}
Run Code Online (Sandbox Code Playgroud)

似乎静态常量有点不同.但上面的内容与OQ中的班级一起工作.

对于更一般的情况,请参阅此问题.


这是用反射完成的:

public static string GetValue(string PropertyName)
{
   return Age.GetType().GetProperty(PropertyName).ToString();
}
Run Code Online (Sandbox Code Playgroud)

注意,GetProperty()可以返回null,如果你传入"F9999"会崩溃

我没有测试过,你可能需要这个:

public static string GetValue(string PropertyName)
{
   return Age.GetType().GetProperty(PropertyName,BindingFlags.Static).ToString();
}
Run Code Online (Sandbox Code Playgroud)

一般情况作为评论:

public static string GetValue(object obj, string PropertyName)
{
   return obj.GetType().GetProperty(PropertyName,BindingFlags.Static).ToString();
}
Run Code Online (Sandbox Code Playgroud)