c# - "Cannot implicitly convert type ' 这个方法<T> ' to ' T '"

标签 c# .net generics compiler-errors

我在使用下面的代码时遇到了问题,希望有人能告诉我它出了什么问题。

我得到的错误是:

Cannot implicitly convert type ThisThing<T> to T

我的代码:

class ThisThing<T>
{
    public string A { get; set; }
    public string B { get; set; }
}

class OtherThing
{
    public T DoSomething<T>(string str)
    {
        T foo = DoSomethingElse<T>(str);
        return foo;
    }

    private T DoSomethingElse<T>(string str)
    {
        ThisThing<T> thing = new ThisThing<T>();
        thing.A = "yes";
        thing.B = "no";

        return thing; // This is the line I'm given the error about
    }
}

想法?感谢您的帮助!

最佳答案

方法 doSomethingdoSomethingElse返回类型为 T ,而您实际上返回的是 thisThing<T>在这些方法的主体中。这些不一样。

举个简单的例子,这相当于返回 List<T>你期望的地方只是T - 它们是完全不同的类别。

关于c# - "Cannot implicitly convert type ' 这个方法<T> ' to ' T '",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8893696/

相关文章:

java - List<Object> abcList 和方法重载

generics - Kotlin 中具有泛型类型的 Lambda val

c# - 我能以某种方式整理这个(过度使用吗?)泛型?

c# - .NET 窗体设计 - 按钮组 "Photoshop Tool Style"

c# - 公开个人资料的可公开查看的 UserId

c# - 所有记录必须存在才能返回记录的 SQL 查询

C#,将数组作为函数参数传递

c# - 找不到终结点 - WCF Web 服务

.net - 无法在 travis 上从命令行让 nuget 工作

.net - Ngen 无需安装程序