无法隐式转换类型'诠释'到'炭',而使用聚合扩展方法 [英] Cannot implicitly convert type 'int' to 'char' while using Aggregate Extension method
问题描述
试图扭转一个字符串,但在聚合函数得到错误
Trying to reverse a string but getting error in Aggregate function
private string Reverse(string strValue)
{
char[] chArray = strValue.ToCharArray();
var reverse = chArray.Reverse();
var res = reverse.Aggregate((a,b)=>a+b);
return res.ToString();
}
无法隐式转换类型'诠释'到'字符。一个显式转换存在(是否缺少强制转换?)
那么,什么是错?
Cannot implicitly convert type 'int' to 'char'. An explicit conversion exists (are you missing a cast?) So what is the mistake?
推荐答案
正是因为它说:结果 A + b
是 INT
,但你希望它是一个字符
。为了得到它的编译的你可以使用:
Exactly as it says: the result of a + b
is an int
, but you want it to be a char
. To get it to compile you can just use:
var res = reverse.Aggregate((a,b)=>(char) (a+b));
...但我不认为这会做你想要什么。
... but I don't think that will do what you want it to.
我建议你不要使用LINQ此入手:
I suggest you don't use LINQ for this to start with:
private string Reverse(string strValue)
{
char[] chArray = strValue.ToCharArray();
Array.Reverse(chArray);
return new string(chArray);
}
请注意,这的不的正常的工作。之类的东西组合字符,代理对等
Note that this doesn't work properly with things like combining characters, surrogate pairs etc.
如果你真的想使用LINQ,可以用做:
If you really wanted to use LINQ, you could do it with:
private string Reverse(string strValue)
{
return new string(strValue.Reverse().ToArray());
}
有没有必要打电话总结
。如果你的真正的想让它慢和使用字符串连接与总结
(这将是为O(n 2 )),你可以做这样的:
There's no need to call Aggregate
. If you really want to make it slow and use string concatenation with Aggregate
(it'll be O(n2)) you can do it like this:
private string Reverse(string strValue)
{
return strValue.Reverse().Aggregate("", (str, c) => str + c);
}
下面是我们所提供的字符串种子值,所以该参数 STR
将是一个字符串, +
将字符串连接,而不是人物的除了的
Here's we've provided a string seed value, so the parameter str
will be a string and +
will be string concatenation, not character addition.
您可以使其使用更高效的的StringBuilder
:
You can make it more efficient using StringBuilder
:
private string Reverse(string strValue)
{
return strValue.Reverse()
.Aggregate(new StringBuilder(), (sb, c) => sb.Append(c))
.ToString();
}
...但我仍然不知道它是值得的......
... but I'm still not sure it's worth it...
这篇关于无法隐式转换类型'诠释'到'炭',而使用聚合扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!