有这样的功能:
private static void EncodeString(ref string str)
{
using (RLE inst_rle = new RLE())
{
string str_encoded = inst_rle.Encode(ref str);
Console.WriteLine(
"\r\nBase string ({0} chars): {1}\r\nAfter RLE-encoding ({2} chars): {3}\r\nCompression percentage: %{4}",
str.Length, str, str_encoded.Length, str_encoded,
() => { (100 * (str.Length - str.encoded.Length) / str.Length); }
);
}
}
正如我记住它的lambda表达式在C#样式:()=> {<动作>; }
但是,让这样的错误:
- 不能lambda表达式转换为类型“对象”,因为它
- 只有转让,电话,递增,递减和新对象表达式可以用作声明
- 不能使用ref或out参数“STR”匿名方法,lambda表达式,或查询表达式内
- 不能使用ref或out参数“STR”匿名方法,lambda表达式,或查询表达式内
如何使用使用LAMBDA在C#EXACLTY在我的应用程序(控制台应用程序)没有明确地
委托/ FUNC <T>,像在() => { }
方式?
我真的不知道你为什么要在这里使用lambda,它看起来像你想要的:
Console.WriteLine(@"\r\nBase string ({0} chars): {1}\r\nAfter RLE-encoding
(
{2} chars): {3}\r\nCompression percentage: {4}",
str.Length, str, str_encoded.Length, str_encoded,
(100 / str.Length) * (str.Length / str_encoded.Length)
);
正如评论指出的那样,你需要用前缀格式字符串@
,因为它跨越多行。
我同意李,但是当你真的想创建一个兰巴这样的,并得到它的输出,你需要显式转换是这样的:
(Func<int>)(() => (100 / str.Length) * (str.Length / str_encoded.Length)))();
我这样做的时候,我与线程在生产代码打,虽然不
字符串常量可以通过使用多个代码行被定义@
前缀,但随后你\r\n
将无法正常工作。 因此,你可以加在一起字符串framgents +
来达到同样的效果:
private static void EncodeString(ref string str)
{
using (RLE inst_rle = new RLE())
{
string str_encoded = inst_rle.Encode(ref str);
Console.WriteLine("\r\nBase string ({0} chars): {1}\r\nAfter RLE-encoding" +
"(" +
"{2} chars): {3}\r\nCompression percentage: {4}",
str.Length, str, str_encoded.Length, str_encoded,
() => { (100 / str.Length) * (str.Length / str_encoded.Length);}
);
}
}
文章来源: Lambda expression C# failed to convert to the object type and fail with ref