Last active
July 28, 2016 04:10
-
-
Save rutcreate/13f9360a2d35a29adff3afeb5f470c07 to your computer and use it in GitHub Desktop.
C# Reflection Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get private or protected field of items | |
FieldInfo fieldInfo = obj.GetType().GetField("items", BindingFlags.NonPublic | BindingFlags.Instance); | |
object field = fieldInfo.GetValue(obj); | |
// Invoke simple method. | |
// instance.Clear(); | |
MethodInfo methodInfo = type.GetMethod("Clear"); | |
methodInfo.Invoke(obj, null); | |
// Invoke method with parameter(s). | |
// instance.MethodWithParams(1, 2, null); | |
MethodInfo methodInfo = type.GetMethod("MethodWithParams"); | |
methodInfo.Invoke(obj, new object[] { 1, 2, null }); | |
// Get generic type. | |
Type genericType = field.GetType().GetGenericArguments()[0]; | |
// Create object from generic method. | |
// A a = new A(); | |
object obj = System.Activator.CreateInstance(genericType); | |
// Access object's field. | |
FieldInfo[] fields = obj.GetType().GetFields(); | |
foreach (FieldInfo info in fields) | |
{ | |
// info.Name | |
// info.SetValue() | |
// ... | |
} | |
// Invoke generic method. | |
// instance.GenericMethodName<T>(); | |
MethodInfo methodInfo = type.GetMethod("GenericMethodName"); | |
MethodInfo genericMethod = methodInfo.MakeGenericMethod(genericType); | |
genericMethod.Invoke(obj, null); | |
// Loop Collection. | |
IEnumerble iter = field as IEnumerable; | |
foreach (var item in iter) | |
{ | |
// Do something with item. | |
} | |
// Count list. | |
ICollection list = field as ICollection; | |
int count = list.Count; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment