泛型类型中众所周知的约束是 new(),可以添加 (args,args,...) 之类的参数来强制编译器检查该类是否包含特定的构造函数?
该块向您展示了这种情况。
public class FooType
{
public FooType(int arg1)
{
}
}
public sealed class FooTypeChildA : FooType
{
public FooTypeChildA(int a) : base(a)
{
}
}
public sealed class FooTypeChildB : FooType
{
public FooTypeChildB() : base(0)
{
}
}
//public class FooConstraint<T> where T : FooType , new() // SUCCESS
//public class FooConstraint<T> where T : FooType , new(int) // ERROR
public class FooConstraint<T> where T : FooType // usually the constraint is "new()", but I need something like this: new(int) that the compiler verify the CHECK_1
{
}
public sealed class Passed : FooConstraint<FooTypeChildA> //[CHECK_1] Pass the constraint.
{
}
public sealed class NotPassed : FooConstraint<FooTypeChildB> //[CHECK_1] Not Pass the constraint.
{
}
这是指令显示可能的语法异常, new(int arg1)
通用实例调用构造函数的方式并不重要,因为基本反射在运行时解决了问题,但想法是强制编译器错误。
ATTEMPT#1 - 这是不可能的;因为接口不能指定构造函数。
public interface IFoo
{
IFoo(int a); // Error here CS0526
}
ATTEMPT#2 - 原始问题已关闭,因为版主专注于在运行时级别而不是编译时级别解决问题。
这个问题在这个问题中没有重复:因为(T)Activator.CreateInstance( typeof(T) , args ) 在您需要非常严格的编译检查时不是一个选项。很明显,Activator 没有完成基本原则(必须尽可能使用派生类和继承行为,而不是它们的最终实现 - Liskov),即保证子类型即使在编译级别也具有父类型的行为。