[英]SetValue Method throw Exception when using reflection
我正在嘗試為許多對象的屬性設置值。 我有一個函數,它接收2個參數MyStructuredObjects和MyObject MyStructuredObjects有一個MyObjects列表。 此函數是一個重構工廠,用於刪除很多“ if”。
我想使用同一對象,因為它的功能是在循環中使用。如果可能的話。 我遇到過異常“對象與目標不匹配”。 很抱歉張貼此,但我沒有發現這樣的問題,使用對象結構內的列表。
看一看 :
public class MyStructuredObjects
{
public List<MyObject1> Object1 { get; set; }
public List<MyObject2> Object2 { get; set; }
public List<MyObject3> Object3 { get; set; }
public List<MyObject4> Object4 { get; set; }
public List<MyObject5> Object5 { get; set; }
}
private void SetValuesToObjectsToIntegrate<T>(ref MyStructuredObjects returnedObject, T obj)
{
Type t = obj.GetType();
var propertyInfo = new ObjectsToIntegrate().GetType().GetProperties();
var instance = Activator.CreateInstance(t);
foreach (var item in returnedObject.GetType().GetProperties())
{
var itemType = item.PropertyType;
if (t == itemType) // PASSING BY HERE OK , it finds the same type :P
{
item.SetValue(t, Convert.ChangeType(obj, item.PropertyType), null);
}
}
}
更新:代碼應為:
item.SetValue(instance, Convert.ChangeType(obj, item.PropertyType), null);
我想我了解您正在嘗試做的事情。
看來您正在嘗試設置以下屬性:
var o2 = new List<MyObject2>();
var mso = new MyStructuredObjects();
SetValuesToObjectsToIntegrate(ref mso, o2);
由於o2
的類型與屬性類型匹配,因此該mso
將設置其屬性Object2
。
如果是這樣,那么您只需要以下代碼:
private void SetValuesToObjectsToIntegrate<T>(MyStructuredObjects returnedObject, T obj)
{
foreach (var propertyInfo in typeof(MyStructuredObjects).GetProperties())
{
if (typeof(T) == propertyInfo.PropertyType)
{
propertyInfo.SetValue(returnedObject, obj, null);
}
}
}
有沒有必要通過MyStructuredObjects returnedObject
由ref
為你不改變的情況下returnedObject
。
使用它來調用此代碼:
var o2 = new List<MyObject2>();
var mso = new MyStructuredObjects();
SetValuesToObjectsToIntegrate(mso, o2);
打電話之后,我得到:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.