C# - 不能在方法中声明委托 [英] C# - Can't declare delegate within a method
问题描述
我真的消隐在这里。
我想知道的为什么我不能宣布一个委托的方法中的类型,而是我在一类一级做。
命名空间delegate_learning
{
类节目
{
//工作正常
公共委托无效anon_delgate(int i)以;
静态无效的主要(字串[] args)
{
玩的开心();
Console.Read();
}
公共静态无效HaveFun()
{
//抛出一个错误:/
//委托无效anon_delgate(int i)以;
anon_delgate广告=委托(int i)以{Console.WriteLine(i.ToString());};
}
}
}
编辑:我研究LAMBDA防爆pressions和备份到它是如何lambda表达式之前,我个人的知识
//抛出一个错误:/
委托无效anon_delgate(int i)以;
它抛出一个错误,因为它是一个的键入的定义,而不是一个的变量的声明。所有的键入的定义里面没有方法允许的。它允许只在类的范围内,或命名空间范围。
命名空间
{
委托无效X(int i)以; //允许
大众B级
{
委托无效Y(int i)以; //也让
}
}
顺便说一句,你为什么不写这样的:
anon_delgate广告= I => Console.WriteLine(i.ToString());
这就是所谓的lambda EX pression。
I'm really blanking out here.
I'm wondering why I can't declare a delegate type within a method, but rather I have to do it at a class level.
namespace delegate_learning
{
class Program
{
// Works fine
public delegate void anon_delgate(int i);
static void Main(string[] args)
{
HaveFun();
Console.Read();
}
public static void HaveFun()
{
// Throws an error :/
//delegate void anon_delgate(int i);
anon_delgate ad = delegate(int i) { Console.WriteLine(i.ToString());};
}
}
}
Edit: I'm researching Lambda Expressions and backing up into how it was before Lambdas, for my own personal knowledge.
// Throws an error :/
delegate void anon_delgate(int i);
It throws an error, because it's a type definition, not a variable declaration. Any type definition is not allowed inside method. It's allowed only at class scope, or namespace scope.
namespace A
{
delegate void X(int i); //allowed
public class B
{
delegate void Y(int i); //also allowed
}
}
By the way, why don't you write this:
anon_delgate ad = i => Console.WriteLine(i.ToString());
It's called lambda expression.
这篇关于C# - 不能在方法中声明委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!