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?
- How to determine which member variable the method parameter represent?
I'm working with Unity3D, so the .net version is 3.5
Aucun commentaire:
Enregistrer un commentaire