c# – 将方法的名称作为参数传递
发布时间:2020-12-15 04:17:16 所属栏目:百科 来源:网络整理
导读:private void Method1(){ //Do something Log("Something","Method1");}private void Method2(){ //Do something Log("Something","Method2");}private void Log(string message,string method){ //Write to a log file Trace.TraceInformation(message + "h
private void Method1() { //Do something Log("Something","Method1"); } private void Method2() { //Do something Log("Something","Method2"); } private void Log(string message,string method) { //Write to a log file Trace.TraceInformation(message + "happened at " + method); } 我有几个方法,如上面的Method1和Method2,我想有一些方法将方法的名称作为参数传递,而无需手动编辑代码. 那可能吗? 解决方法
Jon Skeet的优秀答案.
但是,如果您不使用.NET 4.5,则可以尝试反射.你怎么知道只有在绝对必要时才能使用反射.不要为了使用它而过度使用它. 回来, using System.Reflection; //include Reflection namespace Console.WriteLine(MethodBase.GetCurrentMethod().Name) //Get the method-name of the current method 在你的情况下,它会像下面, private void Method1() { //Do something Log("Something",System.Reflection.MethodBase.GetCurrentMethod().Name); } private void Method2() { //Do something Log("Something",System.Reflection.MethodBase.GetCurrentMethod().Name); } private void Log(string message,string method) { //Write to a log file Trace.TraceInformation(message + "happened at " + method); } 编辑: 根据@Jon Skeet的以下评论,如果你想要.Net 4.5那种花哨而又实用的实现,请查看Micrsoft.Bcl NUGET包. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |