2012-01-17 87 views
2

我在与下面的代码的麻烦,并希望有人在那里能告诉我什么地方错了。“无法隐式转换类型‘thisMethod <T>’到‘T’”

我给出的错误是:

无法隐式转换类型ThisThing<T>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 
    } 
} 

的思考?我感谢您的帮助!

+3

请有资金,都使得它容易得多阅读启动类型名称。而且,请不要用下划线启动局部变量。或者,如果你这样做,用下划线开始它们。这将帮助我们(更重要的是你)阅读代码并防止错误。 – 2012-01-17 11:24:00

回答

2

你告诉了代码,该方法的返回类型为T,你试图返回thisThing<T>。编译器不知道如何将其中一个转换成另一个,所以它向你抱怨。

您需要更改的返回类型的方法或改变你的方法是什么返回。

1
private thisThing<T> doSomethingElse<T>(string thisString) { } 
3

你所要做的是类型thisThing转换为类型T,这是不可能的。相反,你需要改变的doSomethingElse<T>(...)你的返回类型:

private thisThing<T> doSomethingElse<T>(...) { ... } 
7

的方法doSomethingdoSomethingElseT返回类型,而你实际上在这些方法的身体返回thisThing<T>。这些不一样。

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

2

很显然,对我来说

​​是thisThing<T>类型,但返回类型为类型的T

4

那么,编译器说它:

private T doSomethingElse<T>(string thisString) 

将需要:

private thisThing<T> doSomethingElse<T>(string thisString) 

它编译。

现在修复取决于你有什么做的(不使用它的参数的方法是犯罪嫌疑人的话)。

3

thisThing<T>是一个通用型与T作为类型参数。它不能转换为T

这就好比说:

List<string> stringList = new List<string>(); 
string someString = stringList; // Makes no sense. 
0

你可以改变你otherThing类的代码,如下面的代码,并尝试

class otherThing 
    { 
     public otherThing() 
     { 
     } 
     public thisThing<T> doSomething<T>(string thisString) 
     { 
      thisThing<T> foo = doSomethingElse<T>(thisString); 
      return foo; 
     } 
     private thisThing<T> doSomethingElse<T>(string thisString) 
     { 
      thisThing<T> _thisThing = new thisThing<T>(); 
      _thisThing.A = "yes"; 
      _thisThing.B = "no"; 
      return _thisThing; //This is the line I'm given the error about 
     } 
    } 
相关问题