它的名字弦Get属性值 [英] Get property Value by its stringy name

查看:147
本文介绍了它的名字弦Get属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这个类:

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



我wanto编写获得F1,并返回功能18- 25。例如

I wanto to write a function that get "F1" and return "18-25".for example

private string GetValue(string PropertyName)
....

我该怎么办呢?

推荐答案

您可以简单地使用 SWITCH 上述声明要执行的任务:

You can simply use SWITCH statement to perform above task:

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



使用反射,你可以这样做:

Using Reflection, you can do like this:

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

这篇关于它的名字弦Get属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆