“无法隐式转换类型“thisMethod””到“T”
我在使用下面的代码时遇到了问题,希望有人能告诉我它出了什么问题。
我给出的错误是:
无法将类型
ThisThing
隐式转换为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
}
}
想法?我感谢你的帮助!
I'm having trouble with the below code and was hoping someone out there could tell me what's wrong with it.
The error I'm given is:
Cannot implicitly convert type
ThisThing<T>
toT
My code:
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
}
}
Thoughts? I appreciate your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(8)
独闯女儿国2025-01-03 13:29:24
您可以更改您的 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
}
}
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
方法
doSomething
和doSomethingElse
的返回类型为T
,而您实际上返回的是thisThing
> 在这些方法的主体中。这些不一样。举一个简单的例子,这相当于返回
List
,而您期望的只是T
- 它们是完全不同的类。The methods
doSomething
anddoSomethingElse
have a return type ofT
, whereas you're actually returning athisThing<T>
in the body of those methods. These are not the same.For an easy example, this would be equivalent of returning
List<T>
where you expect justT
- they're completely different classes.