C# 反射用法小结
2011-04-02 16:06
441 查看
在C#编程中反射还是蛮常用的,下面是一些简单用法的小结:
class Program { static void Main(string[] args) { Student st = new Student(); object[] argss = { 2, 3 };
// 通过反射调用方法 object resultO = InvokeMethod<Student>("Sum", st, argss); Console.WriteLine(resultO);
// 通过反射调用方法 InvokeMethodSnippet();
// 通过反射给属性赋值 SetValueSnippet();
Console.ReadKey(); } // if invoke a static method, use null for obj. // did not handle the override for parameters. static public object InvokeMethod<T>(string methodName, T obj, object[] args) { System.Reflection.MethodInfo method = typeof(T).GetMethod(methodName); return method.Invoke(obj, args); }
// static public void InvokeMethodSnippet() { object obj = new Student(); string methodName = "Sum"; Type t = obj.GetType(); object[] args = { 2,3 }; object result = t.InvokeMember(methodName, System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, obj, args); Console.WriteLine(result); } // create a new instance static public T CreateNewInstance<T>() { T t = Activator.CreateInstance<T>(); return t; } // get, set value for property static public void SetValueSnippet() { Student st = new Student(); System.Reflection.PropertyInfo info = typeof(Student).GetProperty("Name"); info.SetValue(st, "Nick", null); Console.WriteLine(st.Name); Console.WriteLine(info.GetValue(st, null)); } class Student { public int Sum(int a, int b) { return a + b; } string _name; public string Name { get { return _name; } set { _name = value; } } } }
相关文章推荐
- C# nullable<T> 用法小结
- c# 反射的用法
- c#中反射的用法(即如何根据字符找到已定义的变量)
- c# 反射的用法
- C# String.split()用法小结。String.Split 方法 (String[], StringSplitOptions)
- C# DataTable 用法小结
- C#反射小结
- c#中enum的用法小结
- [C#] 反射的用法
- C# String.split()用法小结
- c#中反射的用法(即如何根据字符找到已定义的变量)
- C#中Enum用法小结
- c# 反射的用法
- c# 反射的用法
- c# 反射的用法(非原创)
- C# List<T> Contains<T>()的用法小结
- C# String.split()用法小结
- C#反射的用法
- c# 反射的用法(非原创)
- C#学习日记2017-04-22 NPOI用法小结(未完待续)