Feedback

Public Fields und Properties via Reflection schreiben

Sprache: C#

Fix: 2012-06-15 – 14.35 Sinn und Zweck Immer wieder kommt es vor, das man Werte innerhalb eines Objektes manipulieren möchte, ohne den exakten Ablauf zur Compile-Zeit zu kennen. Beispiele: - Zugriff auf Strukturen abhängig von Bedingungen zur Laufzeit; zum Beispiel Daten Import/Export. - die Initialisierung von Strings ("" statt null) oder Listen (li = new List<String>() statt li = null). Zu diesem Zweck sind eine Reihe von "generischen" Funktionen entstanden. Funktion SetFieldValue erlaubt das Schreiben auch in verschachtelten Strukturen. Grenzen Als externe Funktion können natürlich nur 'public' Felder und Properties bearbeitet werden. Siehe auch Public Fields und Properties via Reflection lesen Nutzung [code]public partial class Vcard { public String FrontName { get; set; } public String MiddleName { get; set; } public String RearName { get; set; } … } public partial class Info { public Vcard person { get; set; } … } Vcard vcard; Info info; vcard = new Vcard(); vcard.FrontName = "Jane"; vcard.RearName = "Doe"; info = new Info(); info.person = vcard; diub.Generic.xType.SetFieldValue(vcard, "FrontName", "Janet"); diub.Generic.xType.GetFieldValue(info, "person.FrontName", "Janet");[/code]
public class xType {
	public static void SetFieldValue(Object Obj, String FieldName, Object Value) {
	int i;
	String[] part_names;
	Object sub_obj;
	Type type;
	System.Reflection.FieldInfo fi;
	System.Reflection.PropertyInfo pi;

	part_names = FieldName.Split('.');
	sub_obj = Obj;

	for (i = 0; i < part_names.Length - 1; i++) {
		type = sub_obj.GetType();
		fi = type.GetField(part_names[i]);
		if (fi != null) {
			sub_obj = fi.GetValue(sub_obj);
		} else {
			pi = type.GetProperty(part_names[i]);
			sub_obj = pi.GetValue(sub_obj, null);
		}
	}

	type = sub_obj.GetType();
	fi = type.GetField(part_names[part_names.Length - 1]);
	if (fi != null) {
		fi.SetValue(sub_obj, Value);
	} else {
		pi = type.GetProperty(part_names[part_names.Length - 1]);
		pi.SetValue(sub_obj, Value, null);
	}
}
}
public class xType {
	public static void SetFieldValue(Object Obj, String FieldName, Object Value) {
	int i;
	String[] part_names;
	Object sub_obj;
	Type type;
	System.Reflection.FieldInfo fi;
	System.Reflection.PropertyInfo pi;

	part_names = FieldName.Split('.');
	sub_obj = Obj;

	for (i = 0; i < part_names.Length - 1; i++) {
		type = sub_obj.GetType();
		fi = type.GetField(part_names[i]);
		if (fi != null) {
			sub_obj = fi.GetValue(sub_obj);
		} else {
			pi = type.GetProperty(part_names[i]);
			sub_obj = pi.GetValue(sub_obj, null);
		}
	}

	type = sub_obj.GetType();
	fi = type.GetField(part_names[part_names.Length - 1]);
	if (fi != null) {
		fi.SetValue(sub_obj, Value);
	} else {
		pi = type.GetProperty(part_names[part_names.Length - 1]);
		pi.SetValue(sub_obj, Value, null);
	}
}
}