简体   繁体   English

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

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

相关问题 通用 C# - 如何使用反射将属性分配给通用 class - Generic C# - how to use reflection to assign properties to generic class C#中的通用类型返回和参数顺序 - Generic Type Return and Argument order in c# C# 使用反射从方法返回类型的泛型参数中检测可为空的引用类型 - C# detect nullable reference type from generic argument of method's return type using reflection 需要编写一个以我创建的通用类作为参数并解析出属性值的c#方法 - Need to write c# method taking a generic class I create as an argument and parsing out th values of the Properties 没有泛型参数的C#泛型工厂返回 - C# Generic factory return without generic argument 如何使用C#Reflection使用通用代码设置属性和字段? - How to use C# Reflection to set properties and fields with generic code? 在C#中使用反射和通用属性 - Work with reflection and generic properties in C# 如何通过反射检索泛型参数 - How to retrieve generic argument with reflection C# 反射 - 从基类中获取超类的通用参数类型 - C# Reflection - Get Generic Argument type of Super class from within the Base class 在C#中使用反射时,如何将接口指定为通用类型参数? - How to specify an interface as a generic type argument when using reflection in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM