为什么这是不可能的声明方法参数的变种类型这是、不可能、变种、声明

2023-09-04 12:20:58 作者:心易暖亦会涼

我不知道为什么它是不可能的方法参数作为无功型像

 私人无效myMethod的(VAR myvalue的){
   // 做一点事
}
 

解决方案

您只能使用的 VAR 的方法体内的变量。还变量必须声明被分配,它必须能够从在右侧前pression明确推断的类型。

这类证,大学生千万别考 后悔都来不及

在所有其他地方,你必须指定一个类型,即使类型在理论上推断。

的原因是由于该方式,编译器被设计。一个简化的描述是,它首先解析一切,除了方法体,然后使静态类型的每一个类,成员等进行全面分析它解析方法体时再使用此信息,特别是推导当地的类型变量声明为 VAR 。如果 VAR 被允许在任何地方话,那就需要一个大的变化的方式编译工作。

您可以阅读埃里克利珀的关于这个主题的文章了解更多详情:

为什么没有VAR的领域?

I wonder why it is not possible a method parameter as var type like

private void myMethod(var myValue) {
   // do something
}

解决方案

You can only use var for variables inside the method body. Also the variable must be assigned at declaration and it must be possible to deduce the type unambiguously from the expression on the right-hand side.

In all other places you must specify a type, even if a type could in theory be deduced.

The reason is due to the way that the compiler is designed. A simplified description is that it first parses everything except method bodies and then makes a full analysis of the static types of every class, member, etc. It then uses this information when parsing the method bodies, and in particular for deducing the type of local variables declared as var. If var were allowed anywhere then it would require a large change to the way the compiler works.

You can read Eric Lippert's article on this subject for more details:

Why no var on fields?