星期六, 九月 22, 2007

Being more productive with C# 3.0



 
 

Hudong 通过 Google 阅读器发送给您的内容:

 
 

于 07-9-21 通过 MSDN Blogs 作者:Somasegar

The C# language has evolved a lot in the last few years.

With generics, iterators and anonymous methods in C# 2.0, the groundwork was laid for what would eventually become LINQ. Now with C# 3.0 features such as query expressions, lambda expressions and extension methods, LINQ is finally coming to life.

C# 3.0 is about more than just LINQ, however. It's also about the code you write every day, and the little things that make your life easier as a developer. Here are three new C# 3.0 features that let you save time and code, even when you're not writing queries. These features are available in VS 2008 Beta2 if you want to start playing around with them.

Automatic Properties - Many people use public fields just to avoid typing out all that is needed to declare publicly accessible properties. With a new feature called automatic properties, we have made this simple and have removed a lot of repetitive infrastructure from your code. Your code is now as short and simple as public fields. Because they are real properties, you can make implementation changes later without breaking any existing code. Hopefully now you find it easier to resist the temptation to use public fields instead of properties. Check out some examples of how to use these here.

Extension Methods - Sometimes you want to take a private helper method and reuse it elsewhere. Your first thought might be to add the method to one of your own classes as an instance method, but the method may not really operate on any of your own objects. Your only other option would be to make a helper class and add a static method to it. In C# 3.0 you can use the "this" keyword to make an extension method on a common type such as String and your method will appear where it logically belongs. Examples are available here.

Type Inference - The var keyword, which is necessary when using anonymous types, can also reduce redundancy in your other variable declarations. Since the new clause in a declaration makes it obvious what type is being created, you can simply use the var keyword to declare the type instead of typing out a long, repetitive declaration as you often get with generic classes. More details can be found here.

Namaste!


 
 

可从此处完成的操作:

 
 

没有评论:

发表评论