小编Udg*_*gin的帖子

通用方法使用运行时类型执行

这很奇怪,但源代码

public class Processor<T> where T: class
{
...
    private object WorkWithSubtype(IRequester nextRequester, Type type)
    {
        if (type.GetInterface("IList") != null)
        {
            var originalType = type.GetGenericArguments()[0];
            var list = Activator.CreateInstance(type);

            var method = typeof(Processor<>).GetMethod("GetObjects", BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(originalType);
            var resList = method.Invoke(this, new object[] { nextRequester });
            typeof(List<>).GetMethod("AddRange").MakeGenericMethod(originalType).Invoke(list, new object[] { resList });
            return list;
        }
    }

    private IEnumerable<K> GetObjects<K>(IRequester requester) where K: class
    {
        ...
        //We can call method WorkWithSubtype in this method sometimes
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到"无法对ContainsGenericParameters为真的类型或方法执行后期绑定操作." 例外情况是抛出'var resList = method.Invoke(this,new …

.net c# reflection

4
推荐指数
1
解决办法
748
查看次数

标签 统计

.net ×1

c# ×1

reflection ×1