asp.net中mvc從后臺控制器傳遞數(shù)據(jù)到前臺視圖的方式

字號:


    需要添加相應(yīng)的命名空間:
    代碼如下:
    using system;
    using system.diagnostics;
    using system.reflection;
    如果僅是獲取當(dāng)前方法名,可以使用如下代碼:
    代碼如下:
    public static void writesyslog(int level, string content)
    {
    methodbase mb = methodbase.getcurrentmethod();
    string systemmodule = environment.newline;
    systemmodule += 模塊名: + mb.module.tostring() + environment.newline;
    systemmodule += 命名空間名: + mb.reflectedtype.namespace + environment.newline;
    //完全限定名,包括命名空間
    systemmodule += 類名: + mb.reflectedtype.fullname + environment.newline;
    systemmodule += 方法名: + mb.name;
    console.writeline(logdate: {0}{1}level: {2}{1}systemmodule: {3}{1}content: {4}, datetime.now, environment.newline, level, systemmodule, content);
    console.writeline();
    }
    但一般情況下是獲取此記錄日志方法的調(diào)用方,因此需要使用下面的代碼:(此方法僅為演示)
    代碼如下:
    public static void writesyslog(string content)
    {
    const int level = 1000;
    stacktrace ss = new stacktrace(true);
    //index:0為本身的方法;1為調(diào)用方法;2為其上上層,依次類推
    methodbase mb = ss.getframe(1).getmethod();
    stackframe[] sfs = ss.getframes();
    string systemmodule = environment.newline;
    systemmodule += 模塊名: + mb.module.tostring() + environment.newline;
    systemmodule += 命名空間名: + mb.declaringtype.namespace + environment.newline;
    //僅有類名
    systemmodule += 類名: + mb.declaringtype.name + environment.newline;
    systemmodule += 方法名: + mb.name;
    console.writeline(logdate: {0}{1}level: {2}{1}systemmodule: {3}{1}content: {4}, datetime.now, environment.newline, level, systemmodule, content);
    console.writeline();
    }
    對于這一點兒,感覺有意思的是main的調(diào)用方
    代碼如下:
    system.appdomain._nexecuteassembly(assembly assembly, string[] args)
    通過
    代碼如下:
    stacktrace ss = new stacktrace(true);
    stackframe[] sfs = ss.getframes();
    可以得知.net程序的執(zhí)行順序:
    代碼如下:
    system.threading.threadhelper.threadstart()
    system.threading.executioncontext.run(executioncontext executioncontext, contextcallback callback, object state)
    microsoft.visualstudio.hostingprocess.hostproc.runusersassembly()
    system.appdomain._nexecuteassembly(assembly assembly, string[] args)
    然后進入方法main中。
    另外,從 methodbase 類 還可以獲取很多其他屬性,可以自行定位到system.reflection.methodbase 查看。
    使用反射可以遍歷獲得類的所有屬性名,方法名,成員名,其中一個有趣的小例子:通過反射將變量值轉(zhuǎn)為變量名本身。