C# 为什么不能推断委托参数的类型?
我可以这样写:C# 为什么不能推断委托参数的类型?,c#,lambda,delegates,C#,Lambda,Delegates,我可以这样写: new Thread(new ParameterizedThreadStart((x) => //**parameter type not specified explicitly** { for (int j = 0; j < Convert.ToInt32(x); j++) { Console.WriteLine(j); } })).Start(5); new Thread(new ParameterizedThread
new Thread(new ParameterizedThreadStart((x) => //**parameter type not specified explicitly**
{
for (int j = 0; j < Convert.ToInt32(x); j++)
{
Console.WriteLine(j);
}
})).Start(5);
new Thread(new ParameterizedThreadStart(delegate(object x) //**parameter type specified explicitly**
{
for (int j = 0; j < Convert.ToInt32(x); j++)
{
Console.WriteLine(j);
}
})).Start(5);
30 new Thread(new ParameterizedThreadStart(delegate(x) //**parameter type not specified explicitly**
31 {
32 for (int j = 0; j < Convert.ToInt32(x); j++)
33 {
34 Console.WriteLine(j);
35 }
36 })).Start(5);
new Thread(新参数化的threadstart((x)=>/**未明确指定参数类型**
{
对于(int j=0;j
我可以这样写:
new Thread(new ParameterizedThreadStart((x) => //**parameter type not specified explicitly**
{
for (int j = 0; j < Convert.ToInt32(x); j++)
{
Console.WriteLine(j);
}
})).Start(5);
new Thread(new ParameterizedThreadStart(delegate(object x) //**parameter type specified explicitly**
{
for (int j = 0; j < Convert.ToInt32(x); j++)
{
Console.WriteLine(j);
}
})).Start(5);
30 new Thread(new ParameterizedThreadStart(delegate(x) //**parameter type not specified explicitly**
31 {
32 for (int j = 0; j < Convert.ToInt32(x); j++)
33 {
34 Console.WriteLine(j);
35 }
36 })).Start(5);
new Thread(新参数化线程启动(委托(对象x)/**明确指定的参数类型**
{
对于(int j=0;j
但我不能这样写:
new Thread(new ParameterizedThreadStart((x) => //**parameter type not specified explicitly**
{
for (int j = 0; j < Convert.ToInt32(x); j++)
{
Console.WriteLine(j);
}
})).Start(5);
new Thread(new ParameterizedThreadStart(delegate(object x) //**parameter type specified explicitly**
{
for (int j = 0; j < Convert.ToInt32(x); j++)
{
Console.WriteLine(j);
}
})).Start(5);
30 new Thread(new ParameterizedThreadStart(delegate(x) //**parameter type not specified explicitly**
31 {
32 for (int j = 0; j < Convert.ToInt32(x); j++)
33 {
34 Console.WriteLine(j);
35 }
36 })).Start(5);
30新线程(新参数化线程启动(委托(x)/**未明确指定参数类型**
31 {
32表示(int j=0;j
它给出了多个错误:
- 找不到类型或命名空间名称“x”(是否缺少using指令或程序集引用?)-第30行
- 当前上下文中不存在名称“x”-第32行
- 需要标识符-第30行
为什么委托无法推断参数类型?语言设计决策?定义匿名方法有多种方法。这是其中之一:
delegate(object x)
{
}
使用此语法时,必须指定参数类型。代理无法推断参数类型,原因正如您所说的语言设计决策。这与语法有关。此外,使用lambda语法时:
(x) => { ... }
在后台创建委托类型和方法的编译器
注意:也许这个答案没有包含足够的解释,但是你可以看一篇文章来理解它们的区别尽管匿名委托与lambda表达式相似,但它们遵循不同的规则。lambda表达式中的参数类型可以隐式推断,但匿名委托要求您显式指定类型 是的,这是一个语言设计的决定。Lambda表达式是为了支持Linq而引入的,需要显式声明参数类型会使语法不那么方便