簡體   English   中英

可以通過Type實例動態設置泛型類的類型參數嗎?

[英]Can a type parameter of a generic class be set dynamically through a Type instance?

我想做類似下面的代碼。

    public IList SomeMethod(Type t)
    { 
        List<t> list = new List<t>;
        return list;
    }

當然,這是行不通的。 我還有其他方法可以使用對Type實例的引用來動態設置泛型類的type參數嗎?

嘗試這個:

public IList SomeMethod(Type t)
{ 
    Type listType = typeof(List<>);
    listType = listType.MakeGenericType(new Type[] { t});
    return (IList)Activator.CreateInstance(listType);
}

您必須將Type.MakeGenericType()方法與Activator.CreateInstance()一起使用。

生成的代碼丑陋,緩慢,並且使您無法正常運行在編譯時通常會捕獲的錯誤。 這些都不是什么大不了的事,但是我已經看到最后一個特別使其他.Net開發人員(他們期望完全類型安全)措手不及。

就我個人而言,我從來沒有這樣做過。 每當我受到誘惑時,我就把它當作是我的設計有問題的一種征兆,然后再回到制圖板上。 我沒有后悔那門課。

這里沒有其他信息,僅適用於那些遵循以下沙盒代碼的程序(我不得不全部嘗試)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ListFromType
{
    class Program
    {
        static void Main(string[] args)
        {
            var test1 = FlatList(typeof(DateTime));
            var test2 = TypedList<DateTime>(typeof(DateTime));
        }

        public static IList<T> TypedList<T>(Type type)
        {
            return FlatList(type).Cast<T>().ToList();
        }

        public static IList FlatList(Type type)
        {
            var listType = typeof(List<>).MakeGenericType(new Type[] { type });
            var list = Activator.CreateInstance(listType);
            return (IList) list;
        } 
    }
}

你能嘗試像下面這樣嗎,它是泛型類型,

    public IList SomeMethod<T>(T t)
    {
        List<T> list = new List<T>();
        list.Add(t);
        return list;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM