簡體   English   中英

使用反射設置屬性值

[英]Set property value with reflection

我有課程設置

public class Settings
{
  public string A{get;set;}
  public bool B {get;set;}
  public int C {get;set;}
}

我的另一個類我有屬性類型的設置

public class VM
{
   public class Settings Settings{get;set;}
}

我想要具有反射的屬性設置的設置值。

我需要將參數的對象傳遞給InitializeSettings方法。

 public void Init(object viewModel)
    {
        try
        {
            PropertyInfo settings = viewModel.GetType().GetProperty("Settings");

            PropertyInfo[] settingsProperties = settings.PropertyType.GetProperties();

            foreach (PropertyInfo settingsProperty in settingsProperties)
            {
                object value = //load from app.config

                var convertedValue = Convert.ChangeType(value, settingsProperty.PropertyType);

                //how set  value ???
                settingsProperty.SetValue(settings, convertedValue, null);

            }
        }
        catch (Exception exception)
        {
            throw;
        }
    }

此示例代碼完成,但有異常

base = {"Object does not match target type."}

我不知道如何在Init方法中設置viewModel.Settings屬性的值?

你不需要那么復雜。 解壓縮設置對象后,您只需更新:

PropertyInfo settingsProperty = viewModel.GetType().GetProperty("Settings");
Settings settings = (Settings) settingsProperty.GetValue(viewModel);

settings.A = "Foo";
settings.B = true;
settings.C = 123;

這已足以更改存儲在視圖模型中的設置。 如果Settings是值類型,則必須將更改的設置對象寫回對象,如下所示:

settingsProperty.SetValue(viewModel, settings);

但這真的是你所要做的。 當然,如果您知道viewModel屬於VM類型,您只需鍵入它,然后直接訪問該屬性:

Settings settings = ((VM)viewModel).Settings;

因此,不是使用反射,更好的方法是定義一些具有Settings屬性的基類型或接口,並使您的視圖模型實現:

public interface HasSettings
{
    Settings Settings { get; set; }
}

public class VM : HasSettings
{ … }

這樣,您的方法可以接受HasSettings對象而不是普通object ,您可以直接訪問設置對象:

public void Init (HasSettings viewModel)
{
    viewModel.Settings.A = "Foo bar";
}

如果您有不同的Settings類型具有不同的屬性,並且您也希望對它們進行反射,那么您也可以這樣做:

PropertyInfo settingsProperty = viewModel.GetType().GetProperty("Settings");
object settings = settingsProperty.GetValue(viewModel);

for (PropertyInfo prop in settings.GetType().GetProperties())
{
    object value = GetValueForPropertyName(prop.Name); // magic
    prop.SetValue(settings, value);
}

同樣,除非它是值類型,否則無需再寫回設置對象。

暫無
暫無

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

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