0

泛型类型中众所周知的约束是 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),即保证类型即使在编译级别也具有父类型的行为。


4

1 回答 1

1

泛型类型中众所周知的约束是 new(),可以添加 (args,args,...) 之类的参数来强制编译器检查该类是否包含特定的构造函数?

虽然感觉这应该是可用的,但它不是。您只能为无参数构造函数添加约束。

作为替代方案,考虑传递一个工厂函数。在这里,您可以指定输入参数。

public class FooConstraint<T> where T : FooType
{
    private readonly T _myObject;

    public FooConstraint(Func<int, T> generator)
    {
        _myObject = generator(123);
    }
}

注意:您也可以存储它Func本身,而不是立即使用它并丢弃它。这只是一个例子。

由于FooConstraint类定义明确定义了Func<>泛型参数,因此您可以确保其使用者确切知道您将使用FooConstraint哪些构造函数参数来实例化实例。FooConstraintT

var myConstraint = new FooConstraint<FooTypeChildA>(myInt => new FooTypeChildA(myInt));

由于您将始终只是调用构造函数并且从不对 做任何花哨的事情Func,这感觉有点像样板,但鉴于没有真正的通用参数构造函数约束,这是最接近的替代方案。

于 2021-03-25T11:19:59.500 回答