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

时间:2012-08-12 05:55:41

标签: c# c#-4.0 reflection static

请考虑此课程:

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";
}

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

private string GetValue(string PropertyName)
....

我该怎么做?

5 个答案:

答案 0 :(得分:11)

您只需使用SWITCH语句执行上述任务:

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;
    }
}

使用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;
}

答案 1 :(得分:5)

我做了一些测试,对于这种情况,这将起作用:

public static string GetValue(string PropertyName)
{
   return typeof(Age).GetField(PropertyName).GetValue(typeof(Age));
}

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

有关更一般的情况,请参阅this question


这是用反射完成的:

public static string GetValue(string PropertyName)
{
   return Age.GetType().GetProperty(PropertyName).ToString();
}

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

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

public static string GetValue(string PropertyName)
{
   return Age.GetType().GetProperty(PropertyName,BindingFlags.Static).ToString();
}

一般情况作为评论:

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

答案 2 :(得分:1)

使用Linq的反射:

 private string GetValue(string propertyName)
 {
       return typeof(Age).GetFields()
           .Where(field => field.Name.Equals(propertyName))
           .Select(field => field.GetValue(null) as string)
           .SingleOrDefault();
 }

答案 3 :(得分:0)

你应该使用班级Type。 您可以使用getType()函数获取正在使用的类。 使用类型后使用GetProperty函数。 你会得到一个propertyinfo课程。这个类有一个getValue函数。 此值将返回属性的值。

答案 4 :(得分:0)

试试这个并享受:

public static string GetValueUsingReflection(string propertyName)
    {
        var field = Type.GetType("Agenamespace" + "." + "Age").GetField(propertyName, BindingFlags.Public | BindingFlags.Static);
        var fieldValue = field != null ? (string)field.GetValue(null) : string.Empty;
        return fieldValue;
    }

Agenamespace是声明Age类的名称空间。