C# Alle Properties auslesen und deren Value ausgeben.

roker002

Commander
Registriert
Dez. 2007
Beiträge
2.075
Ich versuche gerade von eine Klasse alle Properties auslesen zu lassen und deren Wert anzuzeigen.

Das Problem ist, Wenn ich PropertyInfo verwende und GetValue ausführe, kann ich kein Value zurückbekommen, da GetValue den "this.PropX" erwartet. Wozu brauche ich den Objekt bei GetValue noch ein mal anzugeben um seinen Wert zu bekommen? Das macht doch kein Sinn oder?

Code:
            Object[] properties = this.GetType().GetProperties();
            foreach (Object prop in properties)
            {
                System.Reflection.PropertyInfo pif = (System.Reflection.PropertyInfo)prop;
                Object val = pif.GetValue(prop, null); //<- Hier muss ich den Objekt selbst angeben? Funkioniert auch net!
            }

Wie kann ich sonst über PropertyInfo den Value herausbekommen?
 
Hallo!

Ich habe Dir hier mal eine Methode meines PropertySavers rauskopiert:

Code:
        public static void SaveToFile(object objectToSave, BinaryWriter binaryWriter)
        {
            Type t = objectToSave.GetType();
            binaryWriter.Write(t.ToString());
            PropertyInfo[] propertyInfos = t.GetProperties();
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                if ((propertyInfo.CanRead) & (propertyInfo.CanWrite))
                {
                    object propertyValue = propertyInfo.GetValue(objectToSave, null);
                    Type propertyValueType = propertyValue.GetType();

                    switch (propertyValueType.Name)
                    {
                        case "String":
                            binaryWriter.Write((String)propertyValue);
                            break;
                        case "Int32":
                            binaryWriter.Write((Int32)propertyValue);
                            break;
                        case "DateTime":
                            binaryWriter.Write(((DateTime)propertyValue).Ticks);
                            break;
                        default:
                            throw new NotSupportedException(String.Format("Type '{0}' not supported by PropertySaver.SaveToFile().", propertyValueType.ToString()));
                    }
                }
            }
 
aso... jetzt verstehe ich... da ich von THIS den typ genommen habe, muss ich GetValue(this..) anwenden. hmmm alles klar
 
Zurück
Oben