问题描述
private string path2 = @"C:\abc.txt";
private void button2_Click(object sender, EventArgs e)
{
List<string> Ls = new List<string>();
string path1 = @"C:\abc.txt";
if (Ls.Exists(path1 => path1 == path2))
{
MessageBox.Show("");
}
}
上面列出的代码无法正确编译,因为我声明了path1.I知道lamda:(para)=> (expr)。是那个path1参数?为什么这是增量?因为我是中国人,所以如果你用中文回答并且那不重要,我将非常感激。非常感谢你。
The code listed above can`t be compiled correctly because I declared path1.I know lamda :(para)=>(expr).is that path1 parameter? why that is increct? as I am a chinese,so I will appreciate it if you answer in chinese and that dosn`t matter.thank you very much.
推荐答案
Ls.Exists(x => x == path2)
(x => x == y)
这是x的声明,作为为您生成的匿名方法的参数值。
That is the declaration of "x" as being the parameter value for the anonymous method which is generated for you.
if (collection.Exists(x => x == y))
{
...
编译器有效地扩展以生成:
Effectively gets "expanded" by the compiler to generate:
private bool AnonymousMethod1001(typeOfX x, typeOfY y)
{
return x == y;
}
...
bool result = false;
foreach (typeOfX x in collection)
{
if (anonymousMethod1001(x, y))
{
result = true;
break;
}
}
if (result)
{
...
其中typeOfX和typeOfY是从上下文中推断出来的。
但是......因为这是内联代码,所以你不能在同一范围内声明x,因为当它试图使用它时会混淆系统 - 所以你得到一个编译错误与您的path1,因为它已经在编译器试图找出如何创建匿名方法时声明。
where "typeOfX" and "typeOfY" are inferred from the context.
But...since this is inline code, you can't declare "x" in the same scope, because that would confuse the system when it tried to use it - so you get a compilation error with your path1 because it is already declared when the compiler tried to work out how to create the anonymous method.
using System;
using System.Collections.Generic;
//...
string valueToFind = @"C:\abc.txt";
List<string> listToFindIn = new List<string> { "1", "2", "C:\abc.txt", "3", "2", };
if (listToFindIn.Exists(aValue => aValue == valueToFind))
Console.WriteLine("{0} found", valueToFind);</string></string>
显然,你的变量 path1
(由于某种奇怪的原因等于 path2
)绝对无用且不是没用过任何方式。这就是全部。
如果不够中文,很抱歉。 :-)
Apparently, your variable path1
(by some weird reason equal to path2
) is absolutely useless and isn't used in any way. That's all.
Sorry if it was not Chinese enough. :-)
这篇关于为什么“path1”不需要申报? LAMDA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!