我想知道这是否可能,我想做的是在创建此类的实例时设置列表的类型。
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
}
最佳答案
使用泛型类型定义:
class MyClass<T>
{
private Type _type = typeof(string);
public MyClass()
{
this._type = typeof(T);
}
public List<T> MyList { get; set; } <----it likes this
}
如果您需要接受传入的 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
}
优点是它在列表上强制执行类型约束。只能将给定类型的项目添加到列表中。缺点是您需要转换从中获得的每个项目。如果您避免这种事情并使用上面的通用示例会更好。第三种选择是完全省略泛型:
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
}
这不提供任何类型强制。您的里程可能会有所不同。
关于c# - 动态类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16903921/