![](/img/trans.png)
[英]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.