开发者

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

I want to do something like the code below.

    public IList SomeMethod(Type t)
    { 
        List<t> list = new List<t>开发者_高级运维;
        return list;
    }

This, of course, does not work. Is there some other way I can dynamically set the type parameter of a generic class using a reference to a Type instance?


Try this:

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


You have to use the Type.MakeGenericType() method along with Activator.CreateInstance().

The resulting code is ugly, slow, and opens you up to run time failures for things that you would normally expect to catch at compile time. None of these have to be a huge deal, but I've seen the last one especially catch other .Net developers (who expect full type safety) off guard.

Personally, I've never done it this way. Every time I've been tempted I've taken it as an indication that there's a problem with my design and gone back to the drawing board. I've not regretted that course.


No additional information here, just for those-that-follow sandbox code (I had to try it all out)

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;
        } 
    }
}


can you try doing like following, it is generic type,

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜