问题描述
在C ++中有predefined宏,例如 __功能__
,编译为一个字符串函数名的宏中使用的。
In C++ there are predefined macros such as __FUNCTION__
, which compile to a string literal of the function name the macro is used in.
void MyFunc()
{
printf("I'm in %s!", __FUNCTION__); // I'm in MyFunc!
}
有什么C#的相似?我期待的asp.net web表单做到这一点:
Is there anything similar for C#? I am looking to do this for asp.net web forms:
public string MyProperty
{
get { return (string)ViewState[__PROPERTY__]; }
set { ViewState[__PROPERTY__] = value; }
}
显然,这并不正常工作(否则我不会问这样的问题),我想知道是否有在C#中类似的东西,不使用反射或有任何负面影响性能与使用字符串文字myProperty的
。
这将有望减少错别字我的结束,但我能想到的一些其他情况,但这样做是有益的。
This will hopefully cut down on typos on my end, but I can think of a few other instances where this would be useful.
推荐答案
您可以使用的中的StackFrame得到当前方法的名称
You could use the StackTrace and StackFrame to get the name of the current method
StackTrace st = new StackTrace();
StackFrame sf = st.GetFrame(1);
string method = sf.GetMethod().ToString();
有关的属性,返回的方法名将包括魔术获得_
或集_
prefixes。
For properties, the returned method name will include the magic get_
or set_
prefixes.
不过,我不认为你可以真正重构为一个内联宏或函数这就像你在C ++可以。但是,如果你重构的实用方法干这个,你很可能只是弹出堆栈跟踪退一万步记录来电信息?
However, I don't think you can really refactor this into an inline macro or function like you could in C++. But if you do refactor a utility method to DRY this out, you could probably just pop the StackTrace back one step to log the caller's information?
这篇关于predefined方法名称宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!