簡體   English   中英

使用反射從字典設置屬性

[英]Using reflection to set properties from a dictionary

我有一個帶有一些屬性的對象和一個字典,該字典為每個屬性保留一個臨時值。 該字典的鍵是具有相同屬性名稱的字符串,而值是一個對象。

我要做的是建立一個save方法,該方法讀取字典的鍵並將相應的屬性設置為在字典中找到的值。

所以我想到了反思,但這並不像我想的那么容易。

這是一個示例類:

public class Class{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
    public Dictionary<string, object> Settings { get; set; }

    public void Save()
    {
        foreach (string key in Settings.Keys)
        {
            // PSEUDOCODE
            get the property called like the key
            get its type
            get the value of hte key in the dictionary
            cast this object to the property's value
            set the property to the casted object
        }
    }
}

我之所以不發布代碼,是因為我不知道如何進行轉換和類似的工作,所以我寫了一些偽代碼來讓您了解我要實現的目標。

有沒有人能指出我正確的方向?

這里:

//Get the type
var type= this.GetType();

foreach (string key in Settings.Keys) 
{
    //Get the property
    var property = type.GetProperty(key);
    //Convert the value to the property type
    var convertedValue = Convert.ChangeType(Settings[key], property.PropertyType);
    property.SetValue(this, convertedValue); 
}

未經測試,但應該可以。

暫無
暫無

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

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