C#3.5委托语法(Lambda表达式) [英] C# 3.5 Delegate Syntax (Lambda Expression)
问题描述
订阅我的委托方法时,我只是对奇怪的问题感到困惑:
在以下情况下可以正常工作:
Hi,
I am just confused around strange issue when subscribing my method to delegate:
Work ok on below scenarion:
Public void Test()
{
//Func<int,> objFunc = null; ---------Line 1
//objFunc += (x) => { return x == 5; };--------Line 2
//Func<int,bool> objFunc += (x) =>{ return x == 5; };---------Line 3
}
在上面的代码片段中,如果我注释第3行,则它将编译.但是,如果我注释第1行,第2行和取消注释第3行,则不会编译.
有什么问题?难道这两个东西都一样吗?
请在这方面帮助我.
谢谢!!!
[添加了代码块以提高可读性]
In above code snippet, If I comment Line 3, then it compiles will. But if i comment Line 1 , Line 2 and Uncomment Line 3, it does not compiles.
What is the issue? arent both the things same ?
please help me on this regard.
Thanks!!!
[added code block for better readability]
推荐答案
没有这样的东西订阅我的方法来委托".
您创建一个委托实例,并将匿名方法添加到其调用列表中.
There is no such thing "subscribing my method to delegate".
You create a delegate instance and add an anonymous method to its invocation list.
System.Action<int, string> myAction = null;
myAction += (number, format) => {
System.Console.WriteLine(format, number); //for example
};
System.Action<int, string>
是委托类型,myAction
是委托实例.
您应该理解,在调用列表中添加另一种方法会更改变量的引用标识.
Here System.Action<int, string>
is a delegate type, myAction
is a delegate instance.
You should understand, that adding one more method to the invocation list change referential identity of the variable.
System.Action<int, string> myAction = null;
myAction += (number, format) => {
System.Console.WriteLine(format, number); //for example
};
System.Action<int, string> oldAction == myAction;
myAction += (number, format) => { /*...*/ };
//at this moment, oldAction != myAction; object.ReferenceEquals(oldAction, myAction) == false;
因此,当您执行此操作(+=
)时,将创建一个全新的委托实例并将其分配给变量.换句话说:委托实例是不可变的.为什么?出于与字符串相同的原因:线程安全.
有什么问题吗?
So, when you do this operation (+=
), a brand new delegate instance is created and assigned to a variable. In other words: delegate instances are not mutable. Why? For the same reason as strings: thread safety.
Any questions?
第1行的语法错误.这就是第1行和第2行出错的原因.应该是
Line 1 has the wrong syntax. That is why Lines 1 and 2 are erroring out. It should be
Func<int,bool> objFunc = null;
我认为这里的问题是,在告诉编译器objFUnc是什么之前,您试图为其分配功能..
line1,lin2确保一旦声明了委托,然后为其分配了功能,就可以添加许多类似于line2的功能...
I think the problem here us that before telling the comiler what objFUnc is , u r trying to assign functinality to it..
line1,lin2 makes sure that once delegate is declared and then functionality is assigned to it , many functionalitites similar to line2 can be added...
这篇关于C#3.5委托语法(Lambda表达式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!