c# - 动态类型列表

标签 c# .net

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

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/

相关文章:

c# - 分布式窗口服务

c# - Task.WaitAll 的阻塞等待

.net - EscapeUriString 和 EscapeDataString 有什么区别?

c# - 在代码中获取硬盘上最大的目录大小

c# - 如何在 C# 中不使用 DIRECT SHOW 从网络摄像头获取 YUV 视频数据流?

c# - 选择 MySQL 还是选择 SQL Server Express(免费)?

c# - 如何有效地用流包装字符串(在 .NET 中)?

c# - .Net 发行商策略——原始发行商策略文件?

c# - 无法加载多个 MEF 部件

c# - .NET 中的 Mongodb 单元测试