C# 扩展方法集

语法注意点

  • 可以使用扩展方法来扩展类或接口。
  • 不能重写扩展方法。
  • 扩展方法只能在非嵌套、非泛型静态类内部定义。
  • 扩展方法必须定义在静态类中。
  • 扩展方法的第一个参数的类型用于指定被扩展的类型,它限制该扩展方法只能作用于该类型。
  • 扩展方法的第一个参数必须带有 "this" 修饰符。
  • 调用方必须引入扩展方法的命名空间。
  • 调用扩展方法的语法,与调用 "被扩展的类型上的实例方法" 的语法相同。
  • 调用扩展方法时,无需传递第一个参数,因为该参数仅用于指定被扩展的类型。
  • 扩展方法是一种特殊的静态方法,其调用方式与调用被扩展类型上的实例方法语法相同。
  • 仅当使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。

 

Humanizer(人性化)

Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities

 

string

// Return a string describing the value as a file size.
// For example, 1.23 MB.
public static string ToFileSize(this double value)
{
    string[] suffixes = { "bytes", "KB", "MB", "GB",
        "TB", "PB", "EB", "ZB", "YB"};
    for (int i = 0; i < suffixes.Length; i++)
    {
        if (value <= (Math.Pow(1024, i + 1)))
        {
            return ThreeNonZeroDigits(value /
                Math.Pow(1024, i)) +
                " " + suffixes[i];
        }
    }

    return ThreeNonZeroDigits(value /
        Math.Pow(1024, suffixes.Length - 1)) + 
        " " + suffixes[suffixes.Length - 1];
}
 
// Return the value formatted to include at most three
// non-zero digits and at most two digits after the
// decimal point. Examples:
//         1
//       123
//        12.3
//         1.23
//         0.12
private static string ThreeNonZeroDigits(double value)
{
    if (value >= 100)
    {
        // No digits after the decimal.
        return value.ToString("0,0");
    }
    else if (value >= 10)
    {
        // One digit after the decimal.
        return value.ToString("0.0");
    }
    else
    {
        // Two digits after the decimal.
        return value.ToString("0.00");
    }
}

 

参考资料

扩展方法 (C# 编程指南) (Entrance on MSDN)
http://msdn.microsoft.com/zh-CN/library/bb383977
http://msdn.microsoft.com/zh-cn/magazine/cc163317.aspx

c# 扩展方法奇思妙用
http://www.cnblogs.com/ldp615/archive/2009/08/07/1541404.html

Conversion rules for Instance parameters and their impact
http://blogs.msdn.com/b/sreekarc/archive/2007/10/11/consequences-of-conversion-rules-for-instance-parameters.aspx

Extension methods Interoperability between languages
http://blogs.msdn.com/b/sreekarc/archive/2007/10/11/extension-methods-interoperability-between-languages.aspx

开源扩展项目
http://dnpextensions.codeplex.com/

posted @ 2015-08-05 14:11  霍旭东  阅读(700)  评论(0编辑  收藏  举报