c# - 如何在泛型的 where 子句中指定泛型类?

标签 c# generics c#-4.0

我有以下类和方法:

public class MyGenericClass<T>
    where T : class
{
}

public class MyClass
{
    public TGen MyMethod<TGen>(TGen myGenClass)
        where TGen : MyGenericClass<T>
        where T : class
    {
        return myGenClass;
    }
}

但是,这会报错,因为它无法解析符号 T在我的方法中。我宁愿不必 MyMethod<TGen, T>因为这对我来说似乎有点多余。这可能吗?

最佳答案

您必须指定 T 才能在定义中使用它。编译器无法知道 T 是什么。

所以你应该在使用它之前指定T(在下面的方法级别,或者可能在类级别使用MyClass):

public class MyClass
{
    public TGen MyMethod<TGen, T>(TGen myGenClass)
        where TGen : MyGenericClass<T>
        where T : class
    {
        return myGenClass;
    }
}

您还可以在 where 子句中使用泛型的具体实现:

public class MyClass
{
    public TGen MyMethod<TGen>(TGen myGenClass)
        where TGen : MyGenericClass<DateTime>
    {
        return myGenClass;
    }
}

关于c# - 如何在泛型的 where 子句中指定泛型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10232091/

相关文章:

c# - 将存储为文本的数字转换为数字

oracle - C#中是否有空日期之类的东西

c# - 在 WEB API 方法中处理通用对象的正确方法是什么?

java - 无法使用通配符调用泛型方法

c# - 更新文档中的数组时,如何在 MongoDB 和 C# 中使用 $push 更新修饰符

c# - 使用值和引用参数类型重载的方法

javascript - 是否可以从字符串模板文字中推断泛型类型

visual-studio-2010 - 在 64 位系统上使用 32 位 dll 显示 0x8007000B 错误

c# - WPF控件自定义设计

c# - C# 中的泛型,使用变量类型作为参数