public static class Propertyextension{public static Object Getvaluebyname (This object self, string propertyname)
{ if (self = = null) { return self; } Type t = self. GetType (); PropertyInfo p = t.getproperty (propertyname); Return p.getvalue (self, null);} }
Extension methods:
1 The class where the method resides must be static
The 2 method must also be static
The first parameter of the 3 method must be the type you want to extend, for example if you want to extend a method to int, then the first argument must be int.
4 A This keyword is also required before the first parameter.
String str = "ABC";
object len = Str. Getvaluebyname ("Length");
Attention:
Many people see the expansion method may be in the eyes of the golden, later in the design of the time regardless of 3,721, anyway, can be expanded. Others will arbitrarily extend the class, using some of the previous methods as "Helper" instead of extension methods, note that the extension method is "polluting", so I think in the expansion of the time to think about it is not worth expanding.
Do not extend the higher-level classes at the time of expansion, as I am facing an object extension I think is undesirable, object is the base class of all classes, once extended, all classes are "contaminated".
C # Features-extension methods