是否有一个泛型类型约束的"其中不从"?派生 [英] Is there a generic type-constraint for "where NOT derived from"?

查看:91
本文介绍了是否有一个泛型类型约束的"其中不从"?派生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以指定的来源于的泛型类型参数这样的约束:

We can specify a "derived from" constraint on generic type parameters like this:

class Bar<T> where T : IFooGenerator

是否有指定的的衍生的一种方式?

Is there a way to specify NOT derived from?

我用例:我有一大堆的 FooGenerator 的S中的并行,对每个相同的并行代码,但我们不希望它们的总是的并行化。

My use-case: I have a bunch of FooGenerators that are parallelizable, with the same parallelization code for each, but we don't want them to always be parallelized.

public class FooGenerator : IFooGenerator
{
    public Foo GenerateFoo() { ... }
}

因此,我创建一个通用的容器类并行产生富:

Thus, I create a generic container class for generating Foo in parallel:

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

因为我想 FooGenerator ParallelFooGenerator< FooGenerator> 是可以互换的,我让 ParallelFooGenerator:IFooGenerator 。不过,我显然不希望 ParallelFooGenerator< ParallelFooGenerator> 是合法的。

Since I want FooGenerator and ParallelFooGenerator<FooGenerator> to be interchangeable, I make ParallelFooGenerator : IFooGenerator. However, I clearly don't want ParallelFooGenerator<ParallelFooGenerator> to be legal.

所以,作为辅助的问题。 ,有没有可能是一个更好的方式,如果约束是不可能的不是源于设计这个?

So, as an auxiliary question, is there perhaps a better way to design this if "not derived from" constraints are impossible?

推荐答案

您可以使用类似以下内容:

You could use something like the following:

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;
    }
}

这篇关于是否有一个泛型类型约束的&QUOT;其中不从&QUOT;?派生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆