Edit: For clarifing my problem clearly, I asked a new question .
Edit: Because the reflection solution is impossible, so I changed the title from "Is there any way to get the variable name in C#?" to "How to distinguish class members with same attribute using reflection in C#"
Edit: The variable name is not an accurate meaning, my goal is
I thought I could use Reflection to get the variable info, including its name, but is doesn't work.
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); }
Then, I thought attribute could be the solution.
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
}
}
I'm working with Unity3D, so the .net version is 3.5
Using reflection, it is not possible. After the compilation variable names won't exist, so you can't use reflection at run time to get the name. There are some other methods like expression trees and closures. If you can use them try this.
static string GetVariableName<T>(Expression<Func<T>> expr)
{
var body = (MemberExpression)expr.Body;
return body.Member.Name;
}
To use this kind of functions you can do
GetVariableName(() => someVar)
And if you are using C# 6 a new nameof keyworkd has been added. More info
您可以使用nameof(anyVariable)
,它应该以字符串形式返回任何变量的名称。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.