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
- Getting the variable name using reflection if possible(someone already told me that's impossible).
- Use a solution to get the information added when declaring the member in any circumstance, for example, in the CheckMethod.
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
}
}
Is there any native reflection way to get variable's name?It's impossible- How to determine which member variable the method parameter represent?
I'm working with Unity3D, so the .net version is 3.5