您的位置:首页 > 其它

以非泛型方式调用泛型方法

2007-02-28 23:35 316 查看
通过泛型方法定义具有特定类型意义的方法是常用的手段。但在某些特定情况下,例如在一些通用的框架中,直到运行时才能确定泛型类型参数,就必须通过非泛型方式来调用泛型方法。
假定有这样一个方法:

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

如果想换成这样调用:

Add(Type type, object obj, object list);
通常的方法是这样的:

void Add(Type type, object obj, object list)
public delegate void GM<T>(T obj, IList<T> list);
然后再定义一个非泛型包装的接口:

interface ING
public class GClass<T> : ING
static ING GetNGC(Type genericType, Type methodType, string methodName)

通过执行所返回接口的非泛型方法来达到调用泛型方法的目的:

ING ng = GetNGC(typeof(int), typeof(MyType), "Add");
ng.NGM(i, list);
比对一下,耗时大约是直接泛型调用耗时的三倍。显然这个方案是一个非常实用的方案。归纳一下,一共需要四步:

定义泛型委托;
定义非泛型接口;
实现这个接口;
通过泛型委托获取非泛型接口的实现。

其中前两步比较简单,后两部稍嫌麻烦。于是,我们再进一步实现一个通用的接口实现及其输出。

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;

namespace GenericMethodTest

结论:
以下是测试代码:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace GenericMethodTest

测试结果:

方案耗时比对其他优点
直接调用181不通用
泛型委托包装432.39不通用
反射16538918.78通用,不需额外定义
非泛型接口包装603.33通用,需要额外定义并实现
动态生成的非泛型接口包装724通用,需要额外定义
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: