繁体   English   中英

C#-接受通用参数,使用反射来修改属性,然后返回通用参数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM