我想知道这是否可能,我想要做的是在创建此类的实例时设置列表类型.
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)
使用泛型类型定义:
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)
这不提供任何类型实施.你的旅费可能会改变.
class MyClass <T>
{
public List<T> MyList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)