簡體   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