[英]Generic C# - how to use reflection to assign properties to generic class
[英]C# - Taking a generic argument, use reflection to modify the properties, and return the generic argument
我試圖接受一個通用參數,通過Reflection處理它的屬性,然后返回具有修改后屬性的通用類型。
public IEnumerable<T> GenerateTest()
{
var type = typeof(T);
foreach (var field in type.GetProperties())
{
// Modify / Set properties on variable type
}
// How do I return object T with the parameters that I modified in the iteration above?
}
為了能夠創建一個新的T
對象,您需要將new()
約束添加到type參數:
class MyClass<T> where T : new()
{
public IEnumerable<T> GenerateTest()
{
然后,您可以創建一個新的T
對象並設置其屬性:
var obj = new T();
foreach (var field in typeof(T).GetProperties())
{
field.SetValue(obj, ...);
}
因為您的方法返回了IEnumerable<T>
,所以您不能直接返回T
對象,而需要包裝在一個集合中:
var list = new List<T>();
list.Add(obj);
return list;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.