通过其粗俗的名称获取属性值
请考虑这个课程:
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) ....
我该怎么做?
您只需使用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; }
我做了一些测试,对于这种情况,这将起作用:
public static string GetValue(string PropertyName) { return typeof(Age).GetField(PropertyName).GetValue(typeof(Age)); }
似乎静态常量有点不同。 但上面的内容与OQ中的class级一起工作。
有关更一般的情况,请参阅此问题 。
这是用reflection完成的:
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(); }
使用Linq的reflection:
private string GetValue(string propertyName) { return typeof(Age).GetFields() .Where(field => field.Name.Equals(propertyName)) .Select(field => field.GetValue(null) as string) .SingleOrDefault(); }
你应该使用类Type 。 您可以使用getType()
函数获取正在使用的类。 你有类型后使用GetProperty函数。 你会得到一个propertyinfo类。 这个类有一个getValue函数。 此值将返回属性的值。
尝试这个并享受:
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类的名称空间。