• 使用扩展方法


     来自:http://www.dotnetbips.com/articles/dfeb8a51-4b3b-4bc6-aab9-28ac774b1e8c.aspx

    比如想使用以下代码显示印度格式的时间(Indian Standard Time:IST):

    DateTime dt=DateTime.Now;
    DateTime utc
    = dt.ToUniversalTime();
    DateTime ist
    = utc.AddMinutes(330);

    使用下面2个扩展方法(注意:要用静态类、静态方法还参数中的this):

    namespace Utils
    {
    public static class DateTimeHelper
    {
    public static DateTime ToIST(this DateTime dt)
    {
    DateTime utc
    = dt.ToUniversalTime();
    return utc.AddMinutes(330);
    }

    public static bool IsDate(this string s)
    {
    DateTime dt;
    return DateTime.TryParse(s, out dt);
    }
    }
    }

    这样引用此命名空间后就可以使用扩展方法了:

    注意:

    1. Extension methods can chain themselves. For example you may write something like this: dt.ToIST().ToDDMMYYYY()
      The ToIST() and ToDDMMYYYY() are assumed to be extension methods.
    2. Extension methods can be accessed only when its namespace is in scope
    3. If an extension method has the same signature as any of the instance method of the class it extends then the instance methods take precedence
    4. If two extension methods of a type have same signature them they must be called like normal static methods. For example, if you define two extension methods with same name and signature in two classes say DateTimeHelper1 and dateTimeHelper2, then they can be called  like this - DateTimeHelper1.ToIST(dt)

    更多,更全的扩展方法文章:
    http://www.cnblogs.com/ldp615/archive/2009/08/07/1541404.html


    作者:Net205
    出处:http://net205.cnblogs.com
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    IntelliJ Idea 快捷键列表
    mysql索引类型和方式
    基本git指令
    idea中deBug方法
    BeanUtils.copyProperties(A,B)使用注意事项
    MySQL字段类型
    JAVA常识1
    Redis在windows下的安装下载
    Netty
    IDEA工具
  • 原文地址:https://www.cnblogs.com/net205/p/2033705.html
Copyright © 2020-2023  润新知