当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > C#3.0中实现隐式类型变量、匿名类型的方法

ASP.NET
asp.net SqlParameter关于Like的传参数无效问题
数据库 数据类型float到C#类型decimal, float数据类型转化无效
google suggest 下拉菜单实现代码(asp.net版本)
asp.net(C#) 动态添加非ASP的标准html控件(如添加Script标签)
asp.net GridView导出到Excel代码
asp.net 开发的一些常用技巧
php 三级联动菜单
ASp.net 文本框(TextBox)计算,判断输入的是否是数字
asp.net 存储过程调用
asp.net 操作XML 按指定格式写入XML数据 WriteXml
asp.net连接数据库 增加,修改,删除,查询代码
VB.net 查询获取数据库数据信息
asp.net 删除,更新数据库方法
.net获取硬件信息_CPU序列号
ASP.NET 页面中动态增加的控件、添加事件
彻底解决ASP.NET MD5加密中文结果和ASP不一致的问题
asp.net结合aspnetpager使用SQL2005的存储过程分页
asp.net 用户控件读取以及赋值
asp.net 弹出警告窗口实现代码
asp.net 枚举文件里面的数字绑定到DropDownList里面去

ASP.NET 中的 C#3.0中实现隐式类型变量、匿名类型的方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 231 ::
收藏到网摘: n/a

  本文将向大家介绍一下在C#3.0中实现隐式类型变量、匿名类型的方法,希望对大家有所帮助。

  隐式类型变量 (Implicitly typed local variables)

  象下面的代码书写就是隐式类型变量

以下为引用的内容:
  var i = 5;
  var str = “Csharp”
  var numbers = new int[]{1,2,3};
  var orders = new System.Collections.Hashtable();
  var orders1 = new Dictionary();

  var i = xxx ; 的作用就是用 xxx 的类型声明为i的类型。并给i 赋值。

  由于声明时候,需要依赖于等号右边的表达式,所以必须同时赋值。否则下面的书写就会报错误: Error Implicitly typed locals must be initialized

  var gg;

  使用 Implicitly typed local variables 时应遵守下列约束:

  1. The declarator must include an initializer

  声明时必须包含初始化器。

  2、The initializer must be an expression. The initializer cannot be an object or collection initializer by itself, but it can be a new expression that includes an object or collection initializer.

  初始化必须是一个表达式。初始化表达式不能包含它自身,

  但是可以是包含一个对象或集合初始化器的一个new表达式(即匿名类型)。

  3、The compile-time type of the initializer expression cannot be the null type.

  初始化器表达式的编译期类型不可以是空(null)类型。

  比如:

  var gg = null; 这行代码就会报错误: Cannot assign ’’ to an implicitly typed local

  4、If the local variable declaration includes multiple declarators, the initializers must all have the same compile-time type.

  如果局部变量声明包含了多个声明符,这些声明符必须具备同样的编译期类型。

  比如如下代码:

以下为引用的内容:
  var n = "java"
  var m = 4;
  var ff = m + n;
  Console.WriteLine(ff);
  Console.WriteLine(ff.GetType());

  打印出来的信息会是:

  4.java

  System.String

  5. The initializer cannot refer to itself. (初始化中不能提起它自身)

  隐式类型变量的使用范围,它可不是到处能用。仅仅可以用于下面四种情况

  1. 局部变量声明

  2. for 语句中变量声明)

  3. using 语句初始化变量时.

  4. foreach 中iterator类型声明)