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

ASP.NET
asp.net GridView控件中模板列CheckBox全选、反选、取消
asp.net GridView 删除时弹出确认对话框(包括内容提示)
asp.net DropDownList 三级联动下拉菜单实现代码
asp DataTable添加列和行的三种方法
Asp.net 页面调用javascript变量的值
asp.net 长文章通过设定的行数分页
asp.net 定时间点执行任务的简易解决办法
asp.net 页面延时五秒,跳转到另外的页面
asp.net 动态输出透明gif图片
asp.net DataList与Repeater用法区别
asp.net Javascript获取CheckBoxList的value
asp.net程序在调式和发布之间图片路径问题的解决方法
asp.net下生成英文字符数字验证码的代码
asp.net 页面版文本框智能提示JSCode (升级版)
ASP.NET URL伪静态重写实现方法
ASP.NET 2.0 中Forms安全认证
asp.net 动态添加多个用户控件
asp.net Repeater显示父子表数据,无闪烁
asp.net 无法获取的内部内容,因为该内容不是文本 的解决方法
asp.net GridView排序简单实现

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 64 ::
收藏到网摘: 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类型声明)