Réponses:
Réflexion; pour une instance:
obj.GetType().GetProperties();
pour un type:
typeof(Foo).GetProperties();
par exemple:
class Foo {
public int A {get;set;}
public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}
Suite aux commentaires ...
nullcomme premier argument àGetValueGetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)(qui renvoie toutes les propriétés d'instance publiques / privées).internalpropriétés. Peut-être que je suis le seul à avoir raccroché sur la syntaxe private/ non-public?
using System.Reflectiondirective et le System.Reflection.TypeExtensionspackage sont référencés - cela fournit la surface API manquante via des méthodes d'extension
Vous pouvez utiliser Reflection pour ce faire: (à partir de ma bibliothèque - cela obtient les noms et les valeurs)
public static Dictionary<string, object> DictionaryFromType(object atype)
{
if (atype == null) return new Dictionary<string, object>();
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (PropertyInfo prp in props)
{
object value = prp.GetValue(atype, new object[]{});
dict.Add(prp.Name, value);
}
return dict;
}
Cette chose ne fonctionnera pas pour les propriétés avec un index - pour cela (cela devient trop lourd):
public static Dictionary<string, object> DictionaryFromType(object atype,
Dictionary<string, object[]> indexers)
{
/* replace GetValue() call above with: */
object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{});
}
En outre, pour obtenir uniquement les propriétés publiques: ( voir MSDN sur l'énumération BindingFlags )
/* replace */
PropertyInfo[] props = t.GetProperties();
/* with */
PropertyInfo[] props = t.GetProperties(BindingFlags.Public)
Cela fonctionne aussi sur les types anonymes!
Pour obtenir simplement les noms:
public static string[] PropertiesFromType(object atype)
{
if (atype == null) return new string[] {};
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
List<string> propNames = new List<string>();
foreach (PropertyInfo prp in props)
{
propNames.Add(prp.Name);
}
return propNames.ToArray();
}
Et c'est à peu près la même chose pour les valeurs, ou vous pouvez utiliser:
GetDictionaryFromType().Keys
// or
GetDictionaryFromType().Values
Mais c'est un peu plus lent, j'imagine.
t.GetProperties(BindingFlags.Instance | BindingFlags.Public)out.GetProperties(BindingFlags.Static | BindingFlags.Public)
public List<string> GetPropertiesNameOfClass(object pObject)
{
List<string> propertyList = new List<string>();
if (pObject != null)
{
foreach (var prop in pObject.GetType().GetProperties())
{
propertyList.Add(prop.Name);
}
}
return propertyList;
}
Cette fonction permet d'obtenir la liste des propriétés de classe.
yield return. Ce n'est pas un gros problème, mais c'est une meilleure façon de le faire.
Vous pouvez utiliser l' System.Reflectionespace de noms avec la Type.GetProperties()méthode:
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
Voilà ma solution
public class MyObject
{
public string value1 { get; set; }
public string value2 { get; set; }
public PropertyInfo[] GetProperties()
{
try
{
return this.GetType().GetProperties();
}
catch (Exception ex)
{
throw ex;
}
}
public PropertyInfo GetByParameterName(string ParameterName)
{
try
{
return this.GetType().GetProperties().FirstOrDefault(x => x.Name == ParameterName);
}
catch (Exception ex)
{
throw ex;
}
}
public static MyObject SetValue(MyObject obj, string parameterName,object parameterValue)
{
try
{
obj.GetType().GetProperties().FirstOrDefault(x => x.Name == parameterName).SetValue(obj, parameterValue);
return obj;
}
catch (Exception ex)
{
throw ex;
}
}
}
Je suis également confronté à ce type d'exigence.
De cette discussion, j'ai eu une autre idée,
Obj.GetType().GetProperties()[0].Name
Cela montre également le nom de la propriété.
Obj.GetType().GetProperties().Count();
ce nombre montrant de propriétés.
Merci à tous. C'est une belle discussion.
Voici une réponse @lucasjones améliorée. J'ai inclus les améliorations mentionnées dans la section des commentaires après sa réponse. J'espère que quelqu'un trouvera cela utile.
public static string[] GetTypePropertyNames(object classObject, BindingFlags bindingFlags)
{
if (classObject == null)
{
throw new ArgumentNullException(nameof(classObject));
}
var type = classObject.GetType();
var propertyInfos = type.GetProperties(bindingFlags);
return propertyInfos.Select(propertyInfo => propertyInfo.Name).ToArray();
}