为什么我不能传递一个匿名类型作为参数的函数? [英] Why can't I pass an anonymous type as a parameter to a function?

查看:273
本文介绍了为什么我不能传递一个匿名类型作为参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做类似下面,但它不工作。为什么不会.NET让我做到这一点?

 私人无效的MyFunction(VAR项)
{
 //随你
}
 

解决方案
  

开始在Visual C#3.0,这是在方法范围内声明的变量可以有一个隐式类型变种。一个隐式类型的局部变量是强类型的,就好像你有自己声明的类型,但是编译器确定类型。我下面的两个声明在功能上相当:

 变种I = 10; //隐式类型
INT I = 10; //显式类型
 

。换句话说, VAR 关键字仅允许本地范围的变量。

来源

这一点的详细信息这里。基本上,使用 VAR时还必须初始化变量的值在同一行,这样编译器知道它是什么类型。

I was trying to do something like below but it doesn't work. Why won't .NET let me do this?

private void MyFunction(var items)
{
 //whatever
}

解决方案

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

In otherwords, var keyword is only allowed for locally scoped variables.

Source.

A little bit more info here. Basically, when using var you must also initialize the variable to a value on the same line so that the compiler knows what type it is.

这篇关于为什么我不能传递一个匿名类型作为参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆