【问题标题】:Why can't I have a method in a generic class that takes parameters of a different generic type? [duplicate]为什么我不能在泛型类中拥有一个采用不同泛型类型参数的方法? [复制]
【发布时间】:2019-01-25 16:01:40
【问题描述】:

如果我有这个类:

public class Result<T>
{
}

我想添加一个类似的方法:

public class Result<T>
{
    void DoStuff(Result<T2> otherResult)
    {
        if (otherResult.HasErrors)
            DoWhatever();
    }
}

这是 C# 中的一个错误,但我不明白为什么。只要我不对其他 Result 的 T 做任何事情,编译器为什么会介意?

【问题讨论】:

  • 您尚未在任何地方定义 T2。您遇到的具体错误是什么?

标签: c# generics


【解决方案1】:

因为你没有在任何地方声明T2。你可以这样做:

void DoStuff<T2>(Result<T2> otherResult)
{

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多