C# 反射用法小结
在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 staticmethod, use null for obj. // did not handle the override for parameters.
static public objectInvokeMethod<T>(string methodName, T obj, object[] args) {
System.Reflection.MethodInfo method = typeof(T). GetMethod(methodName);
return method.Invoke(obj, args); }
//
static public voidInvokeMethodSnippet()
{
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 newinstance
static public TCreateNewInstance<T>()
{ T t = Activator.CreateInstance<T>();
return t;
}
// get, set value forproperty static public void SetValueSnippet()
{
Student st = new Student(); System.Reflection. PropertyInfo info = typeof(Stu dent).GetProperty("Name");
info.SetValue(st,"Nick", null);
Console.WriteLine(st.Name);
Console.WriteLine(info.GetValue(st, null)); }
class Student
{
public int Sum(inta, int b) {
return a + b;
}
string _name;
public string Name {
get { return _name; }
set { _name =value; } }
}
}