是否存在"where not derived from"的泛型类型约束?

Blu*_*eft 16 c# generics

我们可以在泛型类型参数上指定"派生自"约束,如下所示:

class Bar<T> where T : IFooGenerator
Run Code Online (Sandbox Code Playgroud)

有没有办法指定NOT派生自?


我的用例:我有一堆FooGenerator可并行化的s,每个都有相同的并行化代码,但我们不希望它们总是被并行化.

public class FooGenerator : IFooGenerator
{
    public Foo GenerateFoo() { ... }
}
Run Code Online (Sandbox Code Playgroud)

因此,我创建了一个用于并行生成Foo的通用容器类:

public class ParallelFooGenerator<T> : IFooGenerator where T : IFooGenerator
{
    public Foo GenerateFoo()
    {
        //Call T.GenerateFoo() a bunch in parallel
    }
}
Run Code Online (Sandbox Code Playgroud)

因为我想要FooGeneratorParallelFooGenerator<FooGenerator>可以互换,我做ParallelFooGenerator : IFooGenerator.但是,我显然不想ParallelFooGenerator<ParallelFooGenerator>合法.

因此,作为一个辅助问题,如果"不是从"约束条件不可能的话,是否有更好的方法来设计它?

Ser*_*rvy 10

您可以使用以下内容:

public interface IFooGenerator
{
    Foo GenerateFoo();
}

interface ISerialFooGenerator : IFooGenerator { }

interface IParallelFooGenerator : IFooGenerator { }

public class FooGenerator : ISerialFooGenerator
{
    public Foo GenerateFoo()
    {
        //TODO
        return null;
    }
}

public class ParallelFooGenerator<T> : IParallelFooGenerator
    where T : ISerialFooGenerator, new()
{
    public Foo GenerateFoo()
    {
        //TODO
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)


cdh*_*wie 7

ParallelFooGenerator<ParallelFooGenerator>已经不可能了,因为ParallelFooGenerator它是泛型类型而你没有指定泛型参数.

例如,ParallelFooGenerator<ParallelFooGenerator<SomeFooGenerator>>可能 - 并允许这样的类型真的那么糟糕?


Ste*_*ves 5

简单回答是不。

长答案(仍然没有):

微软在类型约束的解释中很好地解释了这一点:“编译器必须保证它需要调用的运算符或方法将受到客户端代码可能指定的任何类型参数的支持。”

约束的根本目的不是禁止使用某些类型,而是让编译器知道支持哪些运算符或方法。但是,您可以在运行时检查类型是否实现/继承特定接口/基类并引发异常。不过,这样一来,您将无法从智能感知中获得设计时错误。

我希望这有帮助。