是否有 CallingMemberName-Attribute?

Is there a CallingMemberName-Attribute?

我知道 CallerMemberName 属性,它将空参数替换为例如您从中调用方法的 属性 名称。

这对于 PropertyChanged-Notifications 之类的东西非常有用。目前我们有一个不同的场景,我们希望有一个参数属性,它用您正在调用的方法名称替换空参数。

一般来说,这样可以吗? 老实说,我还没有处理太多自定义属性,但在我们的例子中,拥有这样的东西会很有趣。 有什么有用的信息可以帮助我入手吗?

没有这样的属性,但您可以使用 C# 6 nameof 运算符:

public void SomeMethod ()
{
    Console.WriteLine(nameof(SomeMethod));
}

当然这不会动态地自动插入你所在方法的名称,而是需要你有一个对该方法的实际引用。但是,它支持完整的 IntelliSense,并且还会在您重构方法名称时自动更新。并且名称是在编译时插入的,所以你不会有任何性能下降。

如果你想把这段代码放在更中心的地方,就像你做的那样。基础视图模型中的 INPC 实现,那么你的想法无论如何都有点缺陷。如果你有一个你调用的公共方法来找出你所在的方法名,那么它总是报告公共方法的方法名:

public void SomeMethod ()
{
    Console.WriteLine(GetMethodName());
}

// assuming that a CallingMemberNameAttribute existed
public string GetMethodName([CallingMemberName] string callingMember = null)
{
    return callingMember; // would be always "GetMethodName"
}

但是,您可以在此处再次使用 CallerMemberNameAttribute,这将正确获取调用 GetMethodName 函数的方法名称:

public void SomeMethod ()
{
    Console.WriteLine(GetMethodName());
}

public string GetMethodName([CallerMemberNamed] string callerMember = null)
{
    return callerMember;
}