如何将属性名称字符串转换为对象的属性值

时间:2016-05-02 07:44:33

标签: c# properties

我的许多类都使用字符串插值的DisplayName属性,例如:

  DisplayName = $"{CutoutKind} {EdgeKind} {MaterialKind}";

其中{}中的每个元素都是类属性名称。

我想要做的是检索从数据库插入的字符串,如

displayName = SomeFunction(StringFromDatabase, this);

其中StringFromDatabase是一个变量,从数据库设置值,=" {CutoutKind} {EdgeKind} {MaterialKind}"

但是我想在不使用反射的情况下这样做

是否有一些不同的方式来实现我想要的目标?

1 个答案:

答案 0 :(得分:1)

在运行时不使用反射执行此操作意味着无法使用通用解决方案。您必须为要支持的每个类编写不同的方法。一个非常简单的版本:

static string SomeFunction(string format, MyClass instance)
{
    return format.Replace("{CutoutKind}", instance.CutoutKind.ToString())
                 .Replace("{EdgeKind}", instance.EdgeKind.ToString())
                 .Replace("{EdgeKind}", instance.MaterialKind.ToString());
}

或稍微复杂的版本:

Dictionary<string, Func<MyClass, string>> propertyGetters = 
    new Dictionary<string, Func<MyClass, string>>
    {
        { "CutoutKind", x => x.CutoutKind.ToString() }
        { "EdgeKind", x => x.EdgeKind.ToString() }
        { "EdgeKind", x => x.MaterialKind.ToString() }
    };

static string SomeFunction(string format, MyClass instance)
{
    return Regex.Replace(@"\{(\w+)\}", 
        m => propertyGetters.HasKey(m.Groups[1].Value) 
                 ? propertyGetters[m.Groups[1].Value](instance) 
                 : m.Value;
}

但如果您决定不想为每个课程编写这种方法,那么这里是一个使用反射的简单通用版本:

static string SomeFunction<T>(string format, T instance)
{
    var propertyInfos = typeof(T)
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .ToDictionary(p => p.Name);
    return Regex.Replace(@"\{(\w+)\}", 
        m => propertyInfos.HasKey(m.Groups[1].Value) 
                 ? propertyInfos[m.Groups[1].Value].GetValue(instance, null) 
                 : m.Value;
}
相关问题