Comment obtenir la liste de toutes les propriétés d'une classe ?
Réponses
Trop de publicités?
Sakthivel
Points
89
user3078461
Points
1
public static class AssemblyReader
{
public static object PropertyValueFromName(object atype,string propertyName)
{
var val;
if (atype == null)
return null;
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
foreach (PropertyInfo prp in props)
{
if (prp.Name == propertyName)
val = prp.GetValue(atype);
else
return null;
}
return val;
}
public enum PropertyAccessLevel
{
Public,
Private,
Static,
All
}
public static string[] PropertyNamesWithAccessFromType(object atype, PropertyAccessLevel access)
{
if (atype == null) return new string[] { };
Type t = atype.GetType();
PropertyInfo[] props;
List<string> propNames = new List<string>();
switch (access)
{
case PropertyAccessLevel.All:
props = t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo prp in props)
propNames.Add(prp.Name);
break;
case PropertyAccessLevel.Public:
props = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prp in props)
propNames.Add(prp.Name);
break;
case PropertyAccessLevel.Private:
props = t.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo prp in props)
propNames.Add(prp.Name);
break;
case PropertyAccessLevel.Static:
props = t.GetProperties(BindingFlags.Static | BindingFlags.Instance);
foreach (PropertyInfo prp in props)
propNames.Add(prp.Name);
break;
}
return propNames.ToArray();
}
public static string[] PropertyNamesFromType(object atype)
{
if (atype == null) return new string[] {};
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
List<string> propNames = new List<string>();
foreach (PropertyInfo prp in props)
propNames.Add(prp.Name);
return propNames.ToArray();
}
}
- Réponses précédentes
- Plus de réponses
0 votes
Ce site pourrait également être utile.