我在Visual Studio 2013中使用通用处理程序.
我想要做的是创建一个包含方法名称的URL,但我希望方法的名称是真正的代码,这样它就不会被硬编码,如果函数名称被更改则跟随它.
如果我用C或C++这样做,我会说:
#define GENERATE_REFERENCE(text) #text
Run Code Online (Sandbox Code Playgroud)
我真的不在乎它是一个方法调用,因为我在这里有原型
我在尝试做的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();
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题与方法参考C#中建议的重复问题get methodinfo不同,因为我的问题来自一个对C#机制(新手)非常无知的地方.可疑的重复问题意味着更高层次的理解,远远超出我在我的问题中所表明的理解 - 我不太了解这个问题.我从来没有从我的搜索中找到这个答案.
Ste*_*ler 12
C#6
nameof(MyClass.SayHello)
Run Code Online (Sandbox Code Playgroud)
在C#6之前
public static String GenerateReference<T>(Expression<Action<T>> expression)
{
var member = expression.Body as MethodCallExpression;
if (member != null)
return member.Method.Name;
throw new ArgumentException("Expression is not a method", "expression");
}
GenerateReference<MyClass>(c => c.SayHello(null));
Run Code Online (Sandbox Code Playgroud)
c#6引入了一个新的运算符nameof,它使用方法名称删除这些硬编码字符串.
您可以按如下方式使用它: nameof(Class.Method)
您可以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);
}
}
Run Code Online (Sandbox Code Playgroud)
该示例的优点是在编译时注入字符串(查找元数据没有运行时开销),但它确实要求您保持方法名称同步(例如,如果您重命名“real”,SayHello您还需要重命名的帮手SayHello)。幸运的是,如果您单击“重命名重载”复选框,“重构”对话框将为您执行此操作,但默认情况下它不会打开。