8

Possible Duplicate:
get name of a variable or parameter

I want to be able to get a variable's name as a string.

This can be achieved effectively by using a parameterless lambda expression. However, this has a performance overhead, and it's not built-in functionality.

.NET 4.5 has provided CallerMemberNameAttribute to provide a caller's name as a method argument. This gives us a built-in and better (in some cases) way to do this for specific situations.

.NET 4.5 has provided an improvement in this area for a specific context. Is there now also a better^ means to get any variable's name as a string?

As requested, here's a general usage example of what I'd like to achieve:

//Assume 'myVariable' is a local variable, member variable, static member variable, constant, parameter or even a property.
string myVariableName = ...; //This should get the string name of myVariable

^By better, I mean faster, not requiring reflection, built-into .NET or more elegant, but preferably a combination of these.

4

1 に答える 1

3

いいえ、より良い/より速い方法はありません。リンクした表現ツリーの方法が、変数の名前を取得する唯一の方法だと思います。

、、はCallerMemberNameAttribute、その領域で.NET4.5で導入された唯一の新機能です。CallerFilePathAttributeCallerLineNumberAttribute

于 2012-10-31T10:23:59.610 に答える