编辑:为了清楚地澄清我的问题,我问了一个新的question。
编辑:因为反射解决方案是不可能的,所以我改变了标题“有没有办法在C#中获取变量名?” to“如何使用C#中的反射区分具有相同属性的类成员”
编辑:变量名称不是准确的含义,我的目标是
我以为我可以使用Reflection获取变量信息,包括其名称,但是不起作用。
public class C
{
public List<string> M1{get; set;}
public List<string> M2{get; set;}
}
static void Main(string[] args)
{
C c = new C();
CheckMethod(c.M1);
ChekcMethod(c.M2);
}
void CheckMethod(List<string> m)
{
//Want to get the name "M1" or "M2", but don't know how
Console.Write(m.VariableName);
}
然后,我认为属性可能是解决方案。
public class C
{
[DisplayName("M1")]
public List<string> M1{get; set;}
[DisplayName("M2")]
public List<string> M2{get; set;}
}
static void Main(string[] args)
{
C c = new C();
CheckMethod(c.M1);
ChekcMethod(c.M2);
}
void CheckMethod(List<string> m)
{
//Find all properties with DisplayNameAttribute
var propertyInfos = typeof(C)
.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.GetField | BindingFlags.GetProperty)
.FindAll(pi => pi.IsDefined(typeof(DisplayNameAttribute), true));
foreach (var propertyInfo in propertyInfos)
{
//I can get the DisplayName of all properties, but don't know m is M1 or M2
}
}
我正在使用Unity3D,因此.net版本为3.5
答案 0 :(得分:3)
使用反射,这是不可能的。编译变量名称不存在后,因此无法在运行时使用反射来获取名称。还有一些其他方法,如表达式树和闭包。如果你可以使用它们试试这个。
static string GetVariableName<T>(Expression<Func<T>> expr)
{
var body = (MemberExpression)expr.Body;
return body.Member.Name;
}
要使用此类功能,您可以
GetVariableName(() => someVar)
如果您使用的是C#6,则会添加一个新的keyworkd名称。更多信息
答案 1 :(得分:0)
您可以使用nameof(anyVariable)
,它应该将任何变量的名称作为字符串返回。