簡體   English   中英

如何將屬性名稱的字符串轉換為對象的屬性值

[英]How to to transform a String of Property Names into an object's Property Values

我的許多類都有使用字符串插值的DisplayName屬性,例如:

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

其中{}中的每個元素都是一個類Property Name。

我想做的是從數據庫中檢索要插入的String,類似

displayName = SomeFunction(StringFromDatabase, this);

其中StringFromDatabase是變量,它是從數據庫中設置的值,=“ {CutoutKind} {EdgeKind} {MaterialKind}”

但是我想這樣做而不使用反射

有實現我想要的東西的其他方法嗎?

在運行時執行此操作而不使用反射將意味着不可能使用通用解決方案。 您必須為要支持的每個類編寫不同的方法。 一個非常簡單的版本:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM