繁体   English   中英

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

[英]C# how to force generic argument to be type

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

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

怎么做我要求的?

问题是派生类型是不允许的

没有在运行时检查它就无法强制执行此约束。 这样做将违反Liskov替换原则 ,该原则规定任何类型都应允许您无限制地传递派生类型。

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

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)
{ // ...

如果类型不是结构或密封类,则不可能强制方法只接受一个特定类型,如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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM