如何在tostring()中使用callermembername? [英] How can I use callermembername in tostring()?
问题描述
(相对)新的 CallerMemberName 属性很有用,但我想在ToString()等一些覆盖中使用它。问题是,当我将它添加到我的方法时,签名会发生充分变化,以便不再看到覆盖。
在Visual Studio 2015中,它显示在它下面的红色波浪状指示:
Item.ToString(string):找不到合适的方法来覆盖
哪种有意义,因为我们添加了一个字符串参数,但另一方面却没有,因为它是一个可选参数。有没有办法让这项工作不能创建一个MyToString()并将我的代码中的所有引用更改为?
我尝试过:
The (relatively) new CallerMemberName attribute is useful, but I would like to use it in some overrides like ToString(). The problem is that when I add it to my method, the signature changes sufficiently so that the override is no longer seen as such.
In Visual Studio 2015, it shows a red squiggly under it indicating:
Item.ToString(string): no suitable method found to override
Which sort of makes sense, since we have added a string argument, but on the other hand it doesn't, because it's an optional parameter. Is there a way to make this work short of creating a MyToString() and changing all references in my code to that?
What I have tried:
class Item
{
public override string ToString([CallerMemberName] string caller = null)
{
return base.ToString();
}
}
推荐答案
不能以这种方式使用。这就是错误信息的原因。您可以在此处阅读有关 CallerMemberName
的更多信息: CallerMemberNameAttribute类(System.Runtime.CompilerServices) [ ^ ]
It can't be used that way. That is why the error message is there. You can read more about CallerMemberName
here: CallerMemberNameAttribute Class (System.Runtime.CompilerServices)[^]
这篇关于如何在tostring()中使用callermembername?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!