1

在泛型类的具体实例化期间,是否可以将类型限制为类层次结构的子集。

例如,如果我在创建具体工厂时有一个抽象工厂类,我可以将放入工厂的类型限制为一组有限的类型。

public abstract class AbstractFactory<K,V>

public sealed class CornerProcessorFactory : AbstractFactory<XYZ, Type>

当我声明 CornerProcessorFactory 时,我想限制传递给层次结构中特定基类或接口的类型,但仍然将值类型作为类型而不是实例化类传递。

4

3 回答 3

1

使用类似的东西:

public sealed class CornerProcessorFactory<T> : AbstractFactory<XYZ, T> where T: ISomething

如果您只想对 CornerProcessorFactory 进行限制。

于 2012-09-14T22:08:09.333 回答
0

这是示例代码

public abstract class AbstractFactory<K,V>{}

public sealed class CornerProcessorFactory<K,V> : 
    AbstractFactory<K, V> 
    where K : IFoo 
    where V : struct{ }
于 2012-09-14T22:12:36.403 回答
0

您可以使用 where 关键字来限制您的类型参数:

public abstract class AbstractFactory<TKey, TValue> : SomeOtherGenericClass<TKey>
   where TKey: class, new()
   where TValue: struct

所以在这里,我说 TKey 必须是引用类型并包含默认构造函数,而 TValue 必须是值类型。您还可以指定它从类派生或实现接口。就像是:

   where TKey: IMyInterface

或者

   where TKey: MyBaseClass

所以在第一个中,我基本上要求作为我的 T 传入的任何东西都必须实现 IMyInterface。在第二个中,我要求作为 T 传入的任何内容都必须从 MyBaseClass 派生

于 2012-09-14T22:52:21.030 回答