动态类型列表

DRO*_*ers 2 .net c#

我想知道这是否可能,我想要做的是在创建此类的实例时设置列表类型.

class MyClass
{
    private Type _type = typeof(string);
    public MyClass(Type type)
    {
        this._type = type;
    }

    public List<_type> MyList { get; set; }  <----it does not like this
}
Run Code Online (Sandbox Code Playgroud)

Amy*_*Amy 8

使用泛型类型定义:

class MyClass<T>
{   
    private Type _type = typeof(string);
    public MyClass()
    {
        this._type = typeof(T);
    }

    public List<T> MyList { get; set; }  <----it likes this
}
Run Code Online (Sandbox Code Playgroud)

如果您需要接受传入的Type参数并且泛型不起作用,您可以执行以下操作:

class MyClass
{   
    private Type _type = typeof(string);
    public MyClass(Type type)
    {
        this._type = typeof(type);
        this.MyList = Activator.CreateInstance(typeof(List<>).MakeGenericType(type));
    }

    public IList MyList { get; set; }  <----it likes this
}
Run Code Online (Sandbox Code Playgroud)

优点是它强制列表上的类型约束.只能将给定类型的项添加到列表中.缺点是您需要投射从中获得的每个项目.如果你避免这种事情并使用上面的通用例子会更好.第三种选择是完全忽略泛型:

class MyClass
{   
    private Type _type = typeof(string);
    public MyClass(Type type)
    {
        this._type = typeof(type);
        this.MyList = new ArrayList();
    }

    public IList MyList { get; set; }  <----it likes this
}
Run Code Online (Sandbox Code Playgroud)

这不提供任何类型实施.你的旅费可能会改变.

  • 没有必要设置`_type`.类型可通过`T` Generic类参数获得. (2认同)

Ren*_*nan 6

class MyClass <T>
{
    public List<T> MyList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是我的问题的解决方案.谢谢, (2认同)