Reflection checks whether an object is of a generic set type. Public bool isCollection (object o)
{
Return typeof (ICollection). IsAssignableFrom (o. GetType ())
| Typeof (ICollection <>). IsAssignableFrom (o. GetType ());
}
Obtain a class instance
Public static object Load (string assembly, string className)
{
Return Assembly. Load (assembly). CreateInstance (className );
}
Obtains the specified attribute.
Code Public static PropertyInfo GetPropertyByName (Type type, string propertyName)
{
Return type. GetProperty (propertyName, BindingFlags. Public
| BindingFlags. IgnoreCase | BindingFlags. Instance | BindingFlags. GetProperty | BindingFlags. FlattenHierarchy );
}
Reflection creates a generic set
Code Public static IList CreateList (Type listType)
{
// Type type = listType;
// Reflection creates a common object
Object o = Activator. CreateInstance (listType );
// Reflection creates a generic set
Type generic = typeof (List <> );
Type [] typeArgs = {listType };
Generic = generic. MakeGenericType (typeArgs );
Return Activator. CreateInstance (generic) as IList;
}
Reflection call Method
Code Type dataType = Type. GetType (ClassName );
MethodInfo parseMethod = dataType. GetMethod ("Parse", BindingFlags. Public | BindingFlags. IgnoreCase
| BindingFlags. Static | BindingFlags. FlattenHierarchy, null, new Type [] {typeof (string)}, null );
Reflection gets an Attribute Set (for example, retrieving the columns attribute of a able and traversing it)
DataTable dtSource = (DataTable) data;
Type type = dtSource. GetType ();
PropertyInfo pi = type. GetProperty ("Columns ");
IEnumerable listObject = (IEnumerable) pi. GetValue (dtSource, null );
Reflection setting attributes
Public static void SetPropertyValue (this PropertyInfo property, object target, object value)
{
If (null! = Property & property. CanWrite)
{
If (value. GetType () = typeof (string ))
{
// Converts line breaks.
Value = value. ToString (). Replace ("\ r", "\ r ").
Replace ("\ n", "\ n"). Replace ("<br>", "\ n ");
}
Value = getobjectinstance (property. propertytype, value. tostring ());
Property. setvalue (target, value, null );
}
}