通用抽象列表的子集 - C#

时间:2010-12-30 20:20:44

标签: c# .net generics abstract-class

我正在制作一些抽象基类。基础对象定义为:

    public abstract class Bar
    {
        public bool Enabled;
    }

基本集合定义为:

 public abstract class Foo<T> : List<T>
        where T : Bar
    {
        public Foo<T> GetAllEnabled()
        {
            Foo<T> ret = new Foo<T>();

            foreach (T item in this)
            {
                if (item.Enabled)
                {
                    ret.Add(item);
                }
            }

            return ret;
        }
    }

当然,我在尝试创建new Foo<T>()时遇到错误,因为Foo是一个抽象类。如果没有抽象修饰符,一切都运行正常,但我想要修饰符,因为我想确保该类得到。

我试过了

     Type U = this.GetType();
        Foo ret = new U();
但我收到一个错误“找不到类型或名称空间名称'U'(等等等等)”。

我认为我的尝试修复应该可行,而且我必须让语法错误。我在这里缺少什么?

4 个答案:

答案 0 :(得分:2)

Type U = this.GetType();
Foo ret = new U();

Type U将包含有关数据类型的信息,它不等同于您可以实例化的泛型类型参数。您可以使用U通过Activator.CreateInstance创建一个类型,它有一些重载并接受Type个对象,但是您需要将生成的对象强制转换为适当的类型为了能够使用它。

Type type = this.GetType();
Foo<T> ret = (Foo<T>)Activator.CreateInstance(type);

答案 1 :(得分:1)

but I want the modifier there because I want to make sure the class gets derived.

按照你自己的说法,你需要派生一个你可以实例化的类。

答案 2 :(得分:1)

当然,实例化抽象类Foo<T>是错误的。这是抽象的直接后果。

  

但我想要[abstract]修饰符,因为我想确保该类得到。

然后首先导出它,class Foo2<T> : Foo<T> { },然后实例化Foo2<T>

答案 3 :(得分:0)

您想要创建什么类型?你真的试图去做什么?你为什么要从你的集合类中派生出来?如果你想要它的项目是抽象的,你不需要集合是抽象的。特别是仿制药。

另外:http://blogs.msdn.com/b/codeanalysis/archive/2006/04/27/585476.aspx(我认为有更好的文章,但我找不到)