您的位置:首页 > 编程语言 > C#

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; }
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: