一,类内部调用:
注意点,此时 testFun为public属性
private void button1_Click(object sender, EventArgs e)
{
MethodInfo dynMethod = this.GetType().GetMethod("testFun");
dynMethod.Invoke(this, new object[] { 10, 20 });
}
public void testFun(int a, int b)
{
string msg = a.ToString() + "," + b.ToString();
MessageBox.Show(msg);
}
若此时的 testFun为private属性,则 MethodInfo创建时要添加参数
private void button1_Click(object sender, EventArgs e)
{
MethodInfo dynMethod = this.GetType().GetMethod("testFun", BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new object[] { 10, 20 });
}
private void testFun(int a, int b)
{
string msg = a.ToString() + "," + b.ToString();
MessageBox.Show(msg);
}
二 类外部调用
注意点,此时 testFun为public属性
private void button1_Click(object sender, EventArgs e)
{
HCTestClass theClass = new HCTestClass();
Type theType = theClass.GetType();
MethodInfo dynMethod = theType.GetMethod("testFun");
dynMethod.Invoke(theClass, new object[] { 10, 20 });
}
class HCTestClass
{
public void testFun(int a, int b)
{
string msg = a.ToString() + "," + b.ToString();
MessageBox.Show(msg);
}
}
若此时的 testFun为private属性,则 MethodInfo创建时要添加参数
private void button1_Click(object sender, EventArgs e)
{
HCTestClass theClass = new HCTestClass();
Type theType = theClass.GetType();
MethodInfo dynMethod = theType.GetMethod("testFun", BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(theClass, new object[] { 10, 20 });
}
class HCTestClass
{
private void testFun(int a, int b)
{
string msg = a.ToString() + "," + b.ToString();
MessageBox.Show(msg);
}
}
反射与函数直接调用性能比较
函数直接调用性能,跑10000次在我的电脑上耗时约为10毫秒
private void button1_Click(object sender, EventArgs e)
{
Stopwatch theWatch = new Stopwatch();
theWatch.Start();
for (int i = 0; i < 10000; i++)
{
testFun(10, 20);
}
theWatch.Stop();
this.textBox1.Text = theWatch.ElapsedMilliseconds.ToString();
}
private void testFun(int a, int b)
{
string msg = a.ToString() + "," + b.ToString();
}
反射调用函数性能,跑10000次在我的电脑上耗时约为90毫秒
private void button1_Click(object sender, EventArgs e)
{
Stopwatch theWatch = new Stopwatch();
theWatch.Start();
for (int i = 0; i < 10000; i++)
{
MethodInfo dynMethod = this.GetType().GetMethod("testFun", BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new object[] { 10, 20 });
}
theWatch.Stop();
this.textBox1.Text = theWatch.ElapsedMilliseconds.ToString();
}
private void testFun(int a, int b)
{
string msg = a.ToString() + "," + b.ToString();
}