将C#方法名称转换为文本
我在Visual Studio 2013中使用通用处理程序.
我想要做的是创建一个包含方法名称的URL,但我希望方法的名称是真正的代码,这样它就不会被硬编码,如果函数名称被更改则跟随它. 如果我在C或C中这样做,我会说: #define GENERATE_REFERENCE(text) #text 我真的不在乎它是一个方法调用,因为我在这里有原型 我在尝试做的C#中的“伪代码”: public class MyClass { public void SayHello (String name) { ... } public void GenerateLink() { url = "... "+GenerateReference(this.SayHello); // url would be "... SayHello"; } public String GenerateReference( DataType method ) { // Is there some way to do this? return method.MethodName.ToString(); } } 我的问题与建议的重复问题get methodinfo from a method reference C#不同,因为我的问题来自一个对C#机制(新手)非常无知的地方.可疑的重复问题意味着更高层次的理解,远远超出我在我的问题中所表明的理解 – 我不太了解这个问题.我从来没有从我的搜索中找到这个答案. 解决方法
您可以在参数上使用
CallerMemberNameAttribute ,以便让编译器在早期版本的C#中为您插入名称.
这是一个依赖重载来获得正确答案的示例.请注意,如果您的“真实”方法都有自己的唯一参数,则不需要虚拟重载,并且可以完全避免使用QueryMethodNameHelper参数 // This class is used both as a dummy parameter for overload resolution // and to hold the GetMyName method. You can call it whatever you want class QueryMethodNameHelper { private QueryMethodNameHelper() { } public static readonly QueryMethodNameHelper Instance = new QueryMethodNameHelper(); public static string GetMyName([CallerMemberName] string name = "[unknown]") { return name; } } class Program { // The real method static void SayHello() { Console.WriteLine("Hello!"); } // The dummy method; the parameter is never used,but it ensures // we can have an overload that returns the string name static string SayHello(QueryMethodNameHelper dummy) { return QueryMethodNameHelper.GetMyName(); } // Second real method that has an argument static void DoStuff(int value) { Console.WriteLine("Doing stuff... " + value); } // Dummy method can use default parameter because // there is no ambiguity static string DoStuff(QueryMethodNameHelper dummy = null) { return QueryMethodNameHelper.GetMyName(); } static void Main(string[] args) { string s = SayHello(QueryMethodNameHelper.Instance); Console.WriteLine(s); SayHello(); string s2 = DoStuff(); Console.WriteLine(s2); DoStuff(42); } } 此示例具有在编译时注入字符串的好处(查找元数据没有运行时开销),但它确实要求您保持方法名称同步(例如,如果重命名“真正的”SayHello,则还需要重命名助手SayHello).幸运的是,如果单击“重命名重载”复选框,“重构”对话框将为您执行此操作,但默认情况下它不会打开. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |