C#如何强制泛型参数为type

时间:2012-06-04 17:36:11

标签: c# generics

我有通用的方法。我想要通用方法来限制一种类型。问题是派生类型不被允许 - 我不想要这个。示例代码:

public static T Generate<T>(T input)
    where T : Operation // ALLOWS BinaryOperation - NOT WANT THIS
{
    //...
}

如何做我要求的事情?

2 个答案:

答案 0 :(得分:10)

  

问题是派生类型不允许

没有办法强制执行此约束,而无需在运行时检查它。这样做会违反Liskov Substitution Principle,其中声明任何类型的 都允许您无限制地传入派生类型。

如果必须强制执行此操作,它只能用于运行时检查,例如:

public static T Generate<T>(T input)
    where T : Operation // ALLOWS BinaryOperation - NOT WANT THIS
{
    // Checks to see if it is "Operation" (and not derived type)
    if (input.GetType() != typeof(Operation))
    {
        // Handle bad case here...
    }

    // Alternatively, if you only want to not allow "BinaryOperation", you can do:
    if (input is BinaryOperation)
    {
        // Handle "bad" case of a BinaryOperation passed in here...
    }
}

请注意,在这种情况下,实际上没有理由将其设为通用,因为相同的代码可以用作:

public static Operation Generate(Operation input)
{ // ...

答案 1 :(得分:0)

如果类型不是结构或密封类,则不可能强制方法只接受一个特定类型,如Operation

让我在一个例子中展示这一点,为什么这无论如何都不会起作用:

public void Generate<T>(Operation op) 
    // We assume that there is the keyword "force" to allow only Operation classes
    // to be passed
    where T : force Operation
{ ... }

public void DoSomething()
{
    Generate(new BitOperation()); // Will not build
    // "GetOperation" retrieves a Operation class, but at this point you dont
    // know if its "Operation" or not
    Operation op = GetOperation();
    Generate(op); // Will pass
}

public Operation GetOperation() { return new BitOperation(); }

正如您所见,即使存在限制,也很容易传递BitOperation

解决方案

除了上面提到的其他解决方案之外,只有一个解决方案(结构,密封):运行时检查。 你可以为自己写一个小帮手方法。

public class RuntimeHelper
{
    public static void CheckType<T>(this Object @this)
    {
        if (typeof(T) != @this.GetType())
            throw new ....;
    }
}

用法

public void Generate(Operation op)
{
    op.CheckType<Operation>(); // Throws an error when BitOperation is passed
}

小注

如果您想加快帮助程序,可以使用泛型类RuntimeHelper<T>和静态只读类型变量,其类型为T.

当你这样做时,你不能再使用扩展方法,所以调用将如下所示:

RuntimeHelper<Operation>.CheckType(op);
相关问题