【发布时间】:2010-01-06 18:34:08
【问题描述】:
我需要将泛型类型参数作为接口,但是我想在泛型类 (SomeGenericType) 中实例化该类型,如下所示:
class Program
{
static void Main(string[] args)
{
var val = new SomeGenericType<ISomeInterface>();
Console.ReadKey();
}
}
internal class SomeGenericType<T> where T : new()
{
public SomeGenericType()
{
var test = new T();
}
}
public class SomeClass : ISomeInterface
{
public string TestVal { get; set; }
}
public interface ISomeInterface
{
string TestVal { get; set; }
}
这会引发以下编译时错误:
“ISomeInterface 必须是具有公共无参数构造函数的非抽象类型,才能将其用作泛型类型或方法 SomeGenericType 中的参数 'T'”
我明白为什么会这样,但是我想知道有没有办法解决这个问题?
谢谢。
【问题讨论】:
-
添加额外的约束有帮助吗?
where T : ISomeInterface, new()。正如您所提到的,您将需要为泛型提供一个具体的实现,因为没有其他方法可以保证new()约束。 -
如果你有Interface1,Class1:Interface1,Class2:Interface1,编译器应该如何猜测你是要创建Class1还是Class2的实例?
标签: c# generics constraints