By Mony Hamza

摘至http://www.codeproject.com

Introduction

Well, in this article I'll illustrate some of the C# 3.0 new language and compiler features and I'll illustrate the rest of the features in the second part. First of all, let's define all the new features:

  1. Implicitly Typed Local Variables and Arrays
  2. Object Initializers
  3. Collection Initializers
  4. Extension Methods
  5. Anonymous Types
  6. Lambda Expressions
  7. Query Keywords
  8. Auto-Implemented Properties
  9. Partial Method Definitions

In this article, I will define the first four features with code samples to make it clear.

Implicitly Typed Local Variables and Arrays

Instead of using the explicit type, now we can use the inferred type which means declaring any local variable as var and the type will be inferred by the compiler from the expression on the right side of the initialization statement.
This inferred type could be:

  • Built-in type
  • Anonymous type (will be discussed later)
  • User-defined type
  • Type defined in the .NET Framework class library

Now let's see how local variables can be declared with var:

var int_variable = 6; // int_variable is compiled as an int

var string_variable = "Mony"; // string_variable is compiled as a string

var int_array = new[] { 0, 1, 2 }; // int_array is compiled as int[]

// Query is compiled as IEnumerable

var Query =

from c in customers

where c.Name == "Mony"

select c;

// anonymous_variable is compiled as an anonymous type

var anonymous_variable = new { Name =

var list = new List"Mony", Job = "Web Developer" };

// Implicitly Typed Arrays

var int_array = new[] { 1, 10, 100, 1000 }; // int[]

var string_array = new[] { "hello", null, "world" }; // string[]

Restrictions when using implicitly-typed variables are as follows :

  • var can only be used when you are to declare and initialize the local variable in the same statement.
  • The variable cannot be initialized to null.
  • var cannot be used on fields at class scope.
  • Variables declared by using var cannot be used in the initialization expression. In other words, var i = i++; produces a compile-time error.
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then you will get a compile-time error if you try to initialize a local variable with the var keyword.

Object Initializers

Sometimes you spend a lot of time writing a lot of redundant code to declare constructors that do the same job. Object initializers can be used to initialize types without writing explicit constructors.

Code Example 1

private class Person

{

// Auto-implemented properties

public int Age { get; set; }

public string Name { get; set; }

}

static void Test()

{

// Object initializer

Person per = new Person { Age = 22, Name = "Mony" };

}

Code Example 2

class Point

{

int x, y;

public int X

{

get { return x; }

set { x = value; }

}

public int Y

{

get { return y; }

set { y = value; }

}

}

When you instantiate this class, you normally write the following code:

Point p = new Point();

p.X = 10;

p.Y = 20;

Instead, you can create and initialize a Point object like this:

Point p = new Point { X = 10, Y = 20 }; // object initializer

Or even like this:

var p = new Point { X = 10, Y = 20 }; // object initializer

With complex fields, such as a square or a rectangle whose corners are located at the points p1 and p2, you can create the Rectangle class as follows:

public class Rectangle

{

Point p1;

Point p2;

public Point ULcorner { get { return p1; } set { p1 = value; } }

public Point LRcorner { get { return p2; } set { p2 = value; } }

}

You can create and initialize the Rectangle object like this:

var rectangle = new Rectangle { ULcorner = new Point { X = 0, Y = 0 },

LRcorner = new Point { X = 10, Y = 20 } };

Collection Initializers

Enables initialization of collections with an initialization list rather than specific calls to Add or another method. This initialization has the same effect as using the Add method with each collection element.

public class Person

{

string _Name;

List _Intersets = new List();

public string Name { get { return _Name; } set { _Name =value; } }

public List Interests { get { return _Intersets; } }

}

class Test

{

static void Main(string[] args)

{

List PersonList = new List();

Person p1 = new Person();

p1.Name = "Mony Hamza";

p1.Interests.Add("Reading");

p1.Interests.Add("Running");

PersonList.Add(p1);

Person p2 = new Person();

p2.Name = "John Luke";

p2.Interests.Add("Swimming");

PersonList.Add(p2);

}

}

In C# 3.0, you can write less code to express the same concept:

static void Main(string[] args)

{

var PersonList = new List{

new Person{ Name = "Mony Hamza", Interests = { "Reading", "Running" } },

new Person { Name = "John Luke", Interests = { "Swimming"} };

}

Extension Methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

To create an extension method, declare it as a static method in a static class. The first parameter of an extension method must be the keyword this.

The following is an example of an extension method to convert the temperature from Fahrenheit to Celsius.

namespace MyNameSpace

{

public static class MyClass

{

public static double ConvertToCelsius(this double fahrenheit)

{

return ((fahrenheit – 32) / 1.8); }

}

}

}

Now it is possible to invoke the extension method, ConvertToCelsius, as if it is an instance method:

double fahrenheit = 98.7;

double Celsius = fahrenheit.ConvertToCelsius();

So it adds a method called ConvertToCelisius to an existing type which is double here.

Hope this simple article makes the C# 3.0 new language features quite clear. In the next article, I'll discuss the other five features.

Waiting for your feedback.

转载于:https://www.cnblogs.com/mm8413/archive/2008/01/31/1059766.html

C# 3.0 New Language Features (Part 1)相关推荐

  1. C# 3.0 New Language Features (Part 2)

    By Mony Hamza 摘至http://www.codeproject.com Introduction In the previous article, I illustrated some ...

  2. TypeScript Essential Notes 2 - ES6 Language Features

    syntactic suguar 语法糖 Default parameters Template strings use backtick symbol backtick 反引号 bracket 大括 ...

  3. WARNING: One of the plugins you are using supports Java 8 language features. To try the support buil

    从github上下载一个项目导入到Android studio3.2.0上以后,发现报错:WARNING: One of the plugins you are using supports Java ...

  4. vscode 一直显示Load project: XXXX,保存时提示“从 “‘Vetur‘, ‘Vue Language Features (Volar)‘“ (configure)中获取代码操作”

    问题现象: vscode打开项目之后一直在底部提示一个通知:Load project: 当前项目,如下图所示: 在保存时提示:正在保存"Add.vue": 从 "'Vet ...

  5. 升级 GCC 支持C++11 或 configure: error: *** A compiler with support for C++11 language features is requir

    升级 GCC 支持C++11 或 configure: error: *** A compiler with support for C++11 language features is requir ...

  6. OpenGL 4.0 Shading Language Cookbook-中文版问世了

    OpenGL 4.0 Shading Language Cookbook-中文版问世了, http://item.taobao.com/item.htm?spm=a230r.1.14.13.K3kTO ...

  7. android studio项目报:Error:Jack is required to support java 8 language features. Either enable Jack

    1.问题描述: android studio项目报: Error:Jack is required to support java 8 language features. Either enable ...

  8. Vue Language Features (Volar) 会引起ts报错

    困扰了好一阵子的问题. {"name": "test","version": "0.1.0","private ...

  9. 为所有服务器端代码调用ConfigureAwait的最佳实践

    本文翻译自:Best practice to call ConfigureAwait for all server-side code When you have server-side code ( ...

最新文章

  1. 深入浅出Pytorch:01 课程大纲与PyTorch简介
  2. 分布式系统的发展演变以及RPC简介
  3. Django学习笔记(4)
  4. php ajax session死锁,session过期,ajax请求处理
  5. 敏捷、TDD(测试驱动开发)、OO--前奏
  6. 删除操作记录_微信消费记录能删吗?专家告诉你这样做百分百彻底删除!
  7. 网易云音乐api资料
  8. 程序员,这个双十一,对自己好一点…
  9. 老男孩linux高端运维课程—linux系统目录结构知识讲解
  10. 基于jquery的web在线流程图设计器gooFlow
  11. 用数字计算机公式表白,爱情数学简单表白公式
  12. A卡福利 : AMD Fluid Motion Video补帧教程,让你的视频从24帧补到60帧(144)
  13. 微信公众号系列之创建新浪云平台应用
  14. 笔记一:领导力是什么
  15. 一键加速索尼相机SD卡文件的复制操作,文件操作批处理教程
  16. 什么是对齐,为什么要对齐
  17. java基础题数组_java基础学习——数组笔试题
  18. 真无线蓝牙耳机排名前十的品牌,公认佩戴舒适性好的蓝牙耳机分享
  19. J-Link下载失败解决办法
  20. 4G 物联网连接主力--- LTE Cat1

热门文章

  1. python 制作gif-利用Python如何制作好玩的GIF动图详解
  2. python写软件-Python是怎么编写软件的?
  3. python常用内置模块-Python内置模块和第三方模块
  4. 怎样学好python-怎样学好python
  5. python培训班哪些比较好-学习Python去哪好?哪家Python培训机构比较靠谱
  6. python小课骗局-谈谈学风变python小课感想,菜鸟表示真的挺简单
  7. python小课骗局-python小课值吗
  8. python学不会的表情包-小学生绞尽脑汁也学不会的python(反射)
  9. 没有统计学基础可以学python-如何系统地自学 Python?
  10. python是什么怎么用-什么是python items函数?怎么使用它?