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

ASP.NET
asp.net 动态生成表格
asp.net 程序优化精选
DataGridView自动调整行高和行宽
asp.net+js实现的ajax sugguest搜索提示效果
asp.net 将设有过期策略的项添加到缓存中
asp.net SqlDataAdapter对象使用札记
DataGrid 动态添加模板列 实现代码
asp.net 设置GridView的选中行
the sourcesafe database has been locked by the administrator之解决方法
asp.net 退出登陆(解决退出后点击浏览器后退问题仍然可回到页面问题)
Asp.Net HttpHandler 妙用
ASP.NET 保留文件夹详解
asp.net 中将表单提交到另一页 Code-Behind(代码和html在不同的页面)
SqlDataSource 链接Access 数据
asp.net GridView的删除对话框的两种方法
asp.net 按字节检查包含全半角的文字
asp.net String.IsNullOrEmpty 方法
asp.net System.Net.Mail 发送邮件
c# 读取文件内容存放到int数组 array.txt
asp.net Split分割字符串的方法

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


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