在 .NET 2.0 中享受 .NET 3.0的特性

本文通过实例演示了如何在.NET2.0环境下利用Visual Studio 9.0 (Orcas)实现C#3.0的新特性,如初始化器、自动属性及扩展方法等,并验证了这些特性无需依赖.NET3.0即可使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

众多的新闻不断的向我轰炸,.NET 3.0是如何如何的好,但本人一直做商业产品的开发,看看可以,叫我在开发的产品中使用这些beta的东西,我是万万不敢的,出了问题老板非要宰了我不可。
可是向来对新东西很感兴趣的我,难耐“语法糖”的诱惑,特别是初始化器、自动属性和扩展函数,可以参考下面的文章知道他们的意思。

Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

C# 3.0语言新特性(语言规范):2 扩展方法

从资料上分析,这些特性都是对编译器的改进,理论上.NET下也可以使用这些特性,能不能使用新的 Visual Studio 9.0(Orcas)开发程序,但是还是使用.NET 2.0编译呢?马上就试试看。

下载最新的开发工具后,首先建立一控制台程序,注意在新建对话框的右上角选择.NET 2.0。

首先试验的是初始化器和自动属性,建立下面的程序:

None.gif using  System;
None.gif
using  System.Collections.Generic;
None.gif
None.gif
namespace  ConsoleApplication1
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
static class Program
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            Employee e 
= new Employee dot.gif{ Name = "Hello" };
InBlock.gif            Console.WriteLine(
"OK!{0}", e.Name);
InBlock.gif
InBlock.gif            Console.ReadLine();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public class Employee
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
public string Name dot.gifgetset; }
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

编译,拷贝到仅安装.NET 2.0的机器,OK,非常顺利,反编译程序,发现编译器将你偷懒的东西补充上而已。

那么扩展方法如何呢 ,编写下面的程序:
None.gif using  System;
None.gif
None.gif
using  System.Collections.Generic;
None.gif
using  System.Text;
None.gif
None.gif
namespace  ConsoleApplication1
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
static class Program
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string a = "32";
InBlock.gif            
int b = a.ToInt32();
InBlock.gif            Console.WriteLine(
"Good!{0}",b);
InBlock.gif
InBlock.gif            Console.ReadLine();
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public static int ToInt32(this string s)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return Int32.Parse(s);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

编译,说没有System.Core,这个是.NET 3.0东西,可以吗?管他的,找到DLL直接引用,Run,OK,拷贝到仅安装 .NET 2.0的机器,运行,耶!也OK,删除一并拷贝的System.Core.DLL,晕,还是可以。

总结:
.NET 3.0的很多语法优化都是编译器的功能,与.NET 3.0没有太多关系。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值