扩展方法的使用

标签 AutoCAD Fsharp Csharp

在AutoCAD开发中, 如果想要在命令行输出结果之前插入时间, 你会怎么做?

当然最直接的就是拼接字符串了, 又或者定义静态方法来调用

之前有次在群里, 好多人对我的一段F#代码惊讶不已. 下面就是把好多人雷到的Super Code:

#!fsharp
type Editor with
    member t.WriteWithTime x =
        "[" + DateTime.Now.TimeOfDay.ToString() + "] " + x + "\\n"
        |> t.WriteMessage
let ed = Application.DocumentManager.MdiActiveDocument.Editor
ed.WriteWithTime("带时间的输出风格.")

看到了吗? 我给Editor”增加”了一个WriteWithTime方法! 这叫什么? 狗尾续貂? 貂尾续狗? 汗… 它的学名叫: 扩展方法

如果可以这样写程序会怎么样? "用户密码".MD5() DateTime.GetMyBirthday()

之所以我给[增加]二字括上了引号, 是因为Editor其实没变, 障眼法而已, 人称语法糖, 目的是让你写代码更舒服, 可事实上和定义静态方法也没什么区别, 深入的我也说不清楚, 看看C#3.0该怎么实现这个吧: 注意: 这是C#3.0的新特性, 因此也只能用于VS2008. 更详细的信息请参考: http://msdn.microsoft.com/zh-cn/library/bb383977.aspx

#!csharp
using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
namespace EditorExt
{
    public class Class1
    {
        Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
        [CommandMethod("Test1")]
        public void Test1()
        {
            ed.WriteMessage("WriteMessage - 普通输出.");
        }
        [CommandMethod("Test2")]
        public void Test2()
        {
            ed.WriteWithTime("WriteWithTime - 带时间输出.");
        }
    }
    static class MyExtensionMethods
    {
        // 第一个参数代表要扩展的类 前面加this修饰 调用时只显示一个message参数
        public static void WriteWithTime(this Editor editor, string message)
        {
            editor.WriteMessage("[" + System.DateTime.Now.TimeOfDay.ToString() + "] " + message + "\\n");
        }
    }
}

运行结果:

#!plain
命令: netload
命令: test1
WriteMessage - 普通输出.
命令: test2
[15:52:00.2029960] WriteWithTime- 带时间输出.

命令: Okey如我所愿
未知命令"OKEY如我所愿"。按 F1 查看帮助。

命令: 囧...
未知命令"囧..."。按 F1 查看帮助。