[英]C# Reflection, how to get property instance within class to setvalue
我想在類的方法中將類的屬性重置為默認值。 我的類實例化了一次(實際上是MVVM框架中的ViewModel),我不想破壞並重新創建整個ViewModel,只需要清除許多屬性即可。 下面的代碼是我所擁有的。 我唯一缺少的是如何獲取SetValue方法的第一個參數-我知道它是我正在設置的屬性的實例,但是我似乎無法弄清楚如何訪問它。 我收到錯誤消息:“對象與目標類型不匹配”。
public class myViewModel
{
...
...
public void ClearFields()
{
Type type = typeof(myViewModel);
PropertyInfo[] pi = type.GetProperties();
foreach (var pinfo in pi)
{
object[] attributes = pinfo.GetCustomAttributes(typeof(DefaultValueAttribute), false);
if (attributes.Length > 0)
{
DefaultValueAttribute def = attributes[0] as DefaultValueAttribute;
pinfo.SetValue(?, def.Value, null);
}
}
}
...
...
}
您應該傳遞myViewModel
的實例,在this
情況下,請使用this
來引用當前實例:
public class myViewModel
{
...
...
public void ClearFields()
{
Type type = typeof(myViewModel);
PropertyInfo[] pi = type.GetProperties();
foreach (var pinfo in pi)
{
object[] attributes = pinfo.GetCustomAttributes(typeof(DefaultValueAttribute), false);
if (attributes.Length > 0)
{
DefaultValueAttribute def = attributes[0] as DefaultValueAttribute;
pinfo.SetValue(this, def.Value, null);
}
}
}
...
...
}
您應該this
作為第一個參數。 請參閱MSDN以供參考:
objType:System.Object
將設置其屬性值的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.