【发布时间】:2010-12-31 04:35:51
【问题描述】:
我正在制作一些抽象基类。基础对象定义为:
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 是一个抽象类。没有 abstract 修饰符,一切正常,但我想要修饰符,因为我想确保类得到派生。
我试过了
Type U = this.GetType();
Foo ret = new U();
但我收到一个错误“找不到类型或命名空间名称'U'(等等等等)”。
我认为我尝试的修复应该有效,但我一定是语法错误。我在这里错过了什么?
【问题讨论】:
-
看看
Type.GetConstructor或Activator.CreateInstance。 -
感谢 Eric 和 Anthony,这正是我所需要的。
标签: c# .net generics abstract-class