web-dev-qa-db-fra.com

Comment puis-je obtenir la valeur d'une propriété de chaîne via Reflection?

public class Foo
{
   public string Bar {get; set;}
}

Comment obtenir la valeur de Bar, une propriété de chaîne, par réflexion? Le code suivant lève une exception si le type PropertyInfo est un System.String

Foo f = new Foo();
f.Bar = "Jon Skeet is god.";

foreach(var property in f.GetType().GetProperties())
{
 object o = property.GetValue(f,null); //throws exception TargetParameterCountException for String type
}

Il semble que mon problème est que la propriété est un type indexeur, avec un System.String.

Aussi, comment savoir si la propriété est un indexeur?

19
Alan

Vous pouvez simplement obtenir la propriété par nom:

Foo f = new Foo();
f.Bar = "Jon Skeet is god.";

var barProperty = f.GetType().GetProperty("Bar");
string s = barProperty.GetValue(f,null) as string;

Concernant la question suivante: Les indexeurs seront toujours nommés Item et auront des arguments sur le getter .

Foo f = new Foo();
f.Bar = "Jon Skeet is god.";

var barProperty = f.GetType().GetProperty("Item");
if (barProperty.GetGetMethod().GetParameters().Length>0)
{
    object value = barProperty.GetValue(f,new []{1/* indexer value(s)*/});
}
42
Jake

Je ne pouvais pas reproduire le problème. Êtes-vous sûr que vous n'essayez pas de faire cela sur un objet avec des propriétés d'indexeur? Dans ce cas, l'erreur que vous rencontrez serait renvoyée lors du traitement de la propriété Item . Vous pouvez également procéder comme suit:


public static T GetPropertyValue<T>(object o, string propertyName)
{
      return (T)o.GetType().GetProperty(propertyName).GetValue(o, null);
}

...somewhere else in your code...
GetPropertyValue<string>(f, "Bar");
5
em70
Foo f = new Foo();
f.Bar = "x";

string value = (string)f.GetType().GetProperty("Bar").GetValue(f, null);
4
Handcraftsman
var val = f.GetType().GetProperty("Bar").GetValue(f, null);
4
JP Alioto
Foo f = new Foo();
f.Bar = "Jon Skeet is god.";

foreach(var property in f.GetType().GetProperties())
{
    if(property.Name != "Bar")
    {
         continue;
    }
    object o = property.GetValue(f,null); //throws exception TargetParameterCountException for String type
}

Et voici pour le suivi:

class Test
{
    public class Foo
    {
        Dictionary<string, int> data =new Dictionary<string,int>();
        public int this[string index]
        {
            get { return data[index]; }
            set { data[index] = value; }
        }

        public Foo()
        {
            data["a"] = 1;
            data["b"] = 2;
        }
    }

    public Test()
    {
        var foo = new Foo();
        var property = foo.GetType().GetProperty("Item");
        var value = (int)property.GetValue(foo, new object[] { "a" });
        int i = 0;
    }
}
3
Jake Pearson
PropertyInfo propInfo = f.GetType().GetProperty("Bar");
object[] obRetVal = new Object[0];
string bar = propInfo.GetValue(f,obRetVal) as string;
2
Stan R.

Il est facile d’obtenir la valeur de propriété de n’importe quel objet en utilisant une méthode d’extension comme:

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null);
        }
    }

L'utilisation est:

Foo f = new Foo();
f.Bar = "x";
var balbal = f.GetPropertyValue("Bar");
1
combo_ci

Pour obtenir les noms de propriété de l'objet en passant simplement l'objet, vous pouvez utiliser cette fonction si cela fonctionne.

il suffit de faire objet objet une classe et y passer.

 public void getObjectNamesAndValue(object obj)
    {
        Type type = obj.GetType();
        BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
        PropertyInfo[] prop = type.GetProperties(flags);
        foreach (var pro in prop)
        {
            System.Windows.Forms.MessageBox.Show("Name :" + pro.Name + " Value : "+  pro.GetValue(obj, null).ToString());
        }

    }

Mais cela ne fonctionnera que si les propriétés de l'objet sont "publiques"

0
Sayed idrees

le getvalue avec object et null a fonctionné très bien pour moi. Merci pour les messages.

Contexte: Parcourez toutes les propriétés d'un modèle MVC pour les nouveaux employés et déterminez les valeurs affichées de leurs formulaires:

newHire => le modèle, avec de nombreuses propriétés, dont je veux écrire les valeurs de formulaire postées individuellement dans un ensemble d'enregistrements de base de données

foreach(var propertyValue in newHire.GetProperties())
{
string propName = propertyValue.Name;

string postedValue = newHire.GetType().GetProperty(propName).GetValue(newHire, null).ToString();

}
0
Chris Cherwin