c# - Getting nth property of a class -
am beginner in c# language
i have class
public class plan { int a; int b; int c; }
can in way nth property of class.
for eg: planobject.propertyindex
this of great project, getting index number denoting property value changed. doing right using if...else .
if(index ==1) { planobject.a = 100; } else if(index ==2) { planobject.b = 100; }
is there other solution using reflection?
a word of warning, in no way beginners @ all. , might make code more complex. answer takes granted have working knowledge of extension methods , reflection.
public static class planextension { propertyinfo _info = typeof(plan).getproperties(); public static void setvalue(this plan plan, int index, int value) { var prop = _info[index - 1]; // 1 maps 0.. or 1 in case prop.setvalue(plan, value, null); } public static int getvalue(this plan plan, int index) { var prop = _info[index - 1]; // mapping magic return (int) prop.getvalue(plan, null); } }
called this:
var p = new plan(); p.setvalue(1, 139); // "a" var b = p.getvalue(2); // "b"
it if had definable order properties, name or something. also, error handling must when comes reflection.
Comments
Post a Comment