asp.net中mvc从后台控制器传递数据到前台视图的方式
2015-01-26来源:易贤网

需要添加相应的命名空间:

代码如下:

using system;

using system.diagnostics;

using system.reflection;

如果仅是获取当前方法名,可以使用如下代码:

代码如下:

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();

}

但一般情况下是获取此记录日志方法的调用方,因此需要使用下面的代码:(此方法仅为演示)

代码如下:

public static void writesyslog(string content)

{

const int level = 1000;

stacktrace ss = new stacktrace(true);

//index:0为本身的方法;1为调用方法;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的调用方

代码如下:

system.appdomain._nexecuteassembly(assembly assembly, string[] args)

通过

代码如下:

stacktrace ss = new stacktrace(true);

stackframe[] sfs = ss.getframes();

可以得知.net程序的执行顺序:

代码如下:

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 查看。

使用反射可以遍历获得类的所有属性名,方法名,成员名,其中一个有趣的小例子:通过反射将变量值转为变量名本身。

更多信息请查看IT技术专栏

2026公务员·事业单位培训课程试听报名

  • 报班类型
  • 姓名
  • 手机号
  • 验证码
推荐信息