c#3.0扩展方法的使用
www.dimcax.com
c#3.0扩展方法的使用
如果想要在命令行输出结果之前插入时间, 你会怎么做? 当然最直接的就是拼接字符串了
string msg = datetime.now.timeofday.tostring() + " 你的内容."
editor ed = application.documentmanager.mdiactivedocument.editor;
ed.writemessage(msg)
复制代码
或者定义静态方法来调用 之前有次在群里, 好多人对我的一段f#代码惊讶不已. 下面就是把好多人雷到的super code:
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该怎么实现这个吧:
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");
}
}
}
复制代码
运行结果:
命令: netload
命令: test1
writemessage - 普通输出.
命令: test2
[15:52:00.2029960] writewithtime- 带时间输出.
命令: okey如我所愿
未知命令“okey如我所愿”。按 f1 查看帮助。
命令: 囧...
未知命令“囧...”。按 f1 查看帮助。
复制代码
更详细的信息请参考: [
楼主,偶像啊
晕
路漫漫其修远兮,吾将上下而求索!