[英]C# - Taking a generic argument, use reflection to modify the properties, and return the generic argument
I'm trying to take in a generic argument, manipulate the properties of it via Reflection, and then return the generic type with the modified properties. 我试图接受一个通用参数,通过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?
}
To be able to create a new T
object, you need to add the new()
constraint to the type parameter: 为了能够创建一个新的
T
对象,您需要将new()
约束添加到type参数:
class MyClass<T> where T : new()
{
public IEnumerable<T> GenerateTest()
{
Then you can create a new T
object and set its properties: 然后,您可以创建一个新的
T
对象并设置其属性:
var obj = new T();
foreach (var field in typeof(T).GetProperties())
{
field.SetValue(obj, ...);
}
Because your method returns an IEnumerable<T>
, you can't return your T
object directly but need to wrap in a collection: 因为您的方法返回了
IEnumerable<T>
,所以您不能直接返回T
对象,而需要包装在一个集合中:
var list = new List<T>();
list.Add(obj);
return list;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.