C#变量名转字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15103964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Variable Name To String
提问by user2071747
I have variable
我有变量
public string MyVariable;
I need use name of variable as string. Example:
我需要使用变量名作为字符串。例子:
var a = MyVariable.NameVariable();
// a = "MyVariable"
How i may to do this?
我该怎么做?
I would like to create your miniORM (NHibernate is too heavy and requires a separate library). At the moment the problem is that I have to point out a bunch of constants. For example:
我想创建您的 miniORM(NHibernate 太重了,需要一个单独的库)。目前的问题是我必须指出一堆常量。例如:
public const string FieldIdRules = "idRules"
And then to make transactions in relation samonapisannom profiler. I saw that Hibernate does not need to specify the text value (for the ratio of fields). I want to implement the same.
然后在关系 samonapisannom 分析器中进行交易。我看到Hibernate不需要指定文本值(对于字段的比例)。我想实现相同的。
Sorry my bad english
对不起,我的英语不好
采纳答案by cuongle
Hacky approach, you can get via Expression
:
hacky方法,你可以通过Expression
:
string myVariable = string.Empty;
Expression<Func<object>> expression = () => myVariable;
string name = (expression.Body as MemberExpression).Member.Name;
回答by Ry-
If you can access a variable by name, you already have its name, so type "MyVariable"
.
如果您可以通过名称访问变量,则您已经有了它的名称,因此键入"MyVariable"
.
If you've reassigned it, this is not possible. Values don't keep a history of variable names somewhere.
如果您已重新分配它,则这是不可能的。值不会在某处保留变量名称的历史记录。
So in order to handle field to column mappings, I would suggest a Dictionary
. Reflection is a possibility, but is needlessly complicated for a simple task like that.
因此,为了处理字段到列的映射,我建议使用Dictionary
. 反射是一种可能性,但对于像这样的简单任务来说是不必要的复杂。