【问题标题】:Can I have a different generic type Method in a generic type class我可以在泛型类型类中有不同的泛型类型方法吗
【发布时间】:2019-11-18 13:51:49
【问题描述】:

我想要这样的东西

public class GenericClass<T1> where T1 : class, new()
{
    public void GenericMethod<T2>(GenericClass<T2> t)
    {
        //do my stuff...
    }
}

我遇到了这样的编译错误

类型“T2”必须是引用类型才能在泛型类型或方法“Rextester.GenericClass”中用作参数“T1”

“T2”必须是具有公共无参数构造函数的非抽象类型,才能在泛型类型或方法“GenericClass”中用作参数“T1”

类型 T1 和 T2 没有类型关系。 有可能吗?

【问题讨论】:

  • 那我的语法有什么问题?为什么会出错?
  • 您的语法没有问题。 You don't get an error from this code.
  • OP,您的代码是否过于琐碎而无法实际展示您的问题?
  • 您应该编辑您的问题以包含对GenericClass 的约束,然后将您的固定版本移至答案,以便我们对其进行投票。 :-)
  • 好的。对其他人有好处

标签: c# generic-type-argument


【解决方案1】:

对不起,我的错

public class GenericClass<T1> where T1: class, new()
{
    // <-- I got an error here because I should add same constraint for T2 as it will be used in GenericClass
    public void GenericMethod<T2>(GenericClass<T2> t) 
    // The following line will work fine
    public void GenericMethod<T2>(GenericClass<T2> t) where T2: class, new()
    {
        //do my stuff...
    }
}

【讨论】:

    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多