扩展方法本质上只是一个编译器级别的语法糖, 但不引用.NET Framework 3.5的程序集却无法发布程序到2.0/3.0版本的运行环境中, 因为它将使那些方法(扩展方法)带上ExtensionAttribute属性, 而就是ExtensionAttribute这个类却存在于.NET Framework 3.5的程序集中.

使用一个小技巧即可以保证带有扩展方法的程序在Target到.NET Framework 2.0/3.0时通过编译, 即自己定义这个ExtensionAttribute属性以骗过编译器:
namespace System.Runtime.CompilerServices
{
    
public class ExtensionAttribute : Attribute { }
}

这样, 即使不引用3.5版本的程序集, 依然可以享受扩展方法带来的便利! 事实上, 使用VS 2008在做面向.NET Framework 2.0/3.0的开发时还可以使用许多其他C# 3.0的新语法, 如var以及强大的类型推导等:

示例代码(以下代码在VS 2008, Target to .NET Framework 2.0时编译通过):
using System;
using System.Collections.Generic;
using System.Text;

// trick here~
namespace System.Runtime.CompilerServices
{
    
public class ExtensionAttribute : Attribute { }
}

namespace ConsoleApplication4
{
    
static class Extensions
    {
        
public static int ToInt(this string str)
        {
            
return int.Parse(str);
        }

        
public static void PrintAll<T>(this List<T> obj)
        {
            obj.ForEach(u 
=> Console.WriteLine(u)); // holy lambda!
        }
    }

    
class Program
    {
        
public string AutomaticProperty // automatic property!
        {
            
get;
            
set;
        }

        
static void Main(string[] args)
        {
            var str 
= "3"// var!
            var nine = str.ToInt() * 3// extension method!
            List<int> ints = new List<int>123 }; // collection initializer!
            ints.PrintAll(); // type inference + extension method!
            var anonymousObj = new { FieldA = "asdf", FieldB = "qwer" }; // anonymous type!
            new Program
            {
                AutomaticProperty 
= "value" // i forget this feature's name!
            };
            
// any more?
        }
    }
}

所以.. 即使你只是写面向.NET Framework 2.0的程序.. 使用VS 2008开发还是可以获得许多便利哦~

Reference: Extension Methods without 3.5 Framework

Posted on 2007-11-17 22:19  Adrian H.  阅读(1054)  评论(0编辑  收藏  举报