结论:
以下是测试代码:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace GenericMethodTest


{
// 为泛型方法定义的委托
public delegate void GM<T>(T obj, IList<T> list);

// 为非泛型方法定义的接口
public interface ING

{
void NGM(object obj, object list);
}

class Program

{
static void Main(string[] args)

{
List<int> list = new List<int>();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Reset();
watch.Start();
for (int i = 0; i < 1000000; i++)

{
list.Add(i);
}
watch.Stop();
long l1 = watch.ElapsedMilliseconds;
watch.Reset();
watch.Start();
GM<int> gm = new GM<int>(Program.Add);
for (int i = 0; i < 1000000; i++)

{
gm(i, list);
}
watch.Stop();
long l2 = watch.ElapsedMilliseconds;
watch.Reset();
watch.Start();
MethodInfo mi = typeof(Program).GetMethod("Add");
MethodInfo gmi = mi.MakeGenericMethod(typeof(int));
for (int i = 0; i < 1000000; i++)

{

gmi.Invoke(null, new object[]
{ i, list });
}
watch.Stop();
long l3 = watch.ElapsedMilliseconds;
watch.Reset();
watch.Start();
ING ng1 = GetNGC(typeof(int), typeof(Program), "Add");
for (int i = 0; i < 1000000; i++)

{
ng1.NGM(i, list);
}
watch.Stop();
long l4 = watch.ElapsedMilliseconds;
watch.Reset();
watch.Start();
ING ng2 = InterfaceGenerator.GetInterface<ING>(new GM<int>(Program.Add));
for (int i = 0; i < 1000000; i++)

{
ng2.NGM(i, list);
}
watch.Stop();
long l5 = watch.ElapsedMilliseconds;
Console.WriteLine("{0}\n{1} vs {2} vs {3} vs {4} vs {5}", list.Count, l1, l2, l3, l4, l5);
Console.ReadLine();
}

public static void Add<T>(T obj, IList<T> list)

{
list.Add(obj);
}

static ING GetNGC(Type genericType, Type methodType, string methodName)

{
MethodInfo mi = methodType.GetMethod(methodName);
MethodInfo gmi = mi.MakeGenericMethod(genericType);
Delegate gmd = Delegate.CreateDelegate(typeof(GM<>).MakeGenericType(genericType), gmi);
return Activator.CreateInstance(typeof(GClass<>).MakeGenericType(genericType), gmd) as ING;
}
}

public class GClass<T> : ING

{
private GM<T> m_gmd;

public GClass(GM<T> gmd)

{
m_gmd = gmd;
}


INGClass 成员#region INGClass 成员

public void NGM(object obj, object list)

{
m_gmd((T)obj, (IList<T>)list);
}

#endregion
}
}

测试结果:
方案 | 耗时 | 比对 | 其他优点 |
直接调用 | 18 | 1 | 不通用 |
泛型委托包装 | 43 | 2.39 | 不通用 |
反射 | 16538 | 918.78 | 通用,不需额外定义 |
非泛型接口包装 | 60 | 3.33 | 通用,需要额外定义并实现 |
动态生成的非泛型接口包装 | 72 | 4 | 通用,需要额外定义 |
转载于:https://blog.51cto.com/kanas/285945