栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用仅在执行时已知的类型参数调用泛型方法[重复]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用仅在执行时已知的类型参数调用泛型方法[重复]

编辑:好的,时间短但完整的程序。基本答案与以前相同:

  • 使用Type.GetMethod查找“开放”通用方法
  • 使用MakeGenericMethod使其通用
  • 用调用来调用

这是一些示例代码。请注意,我已将查询表达式更改为点表示法-当您基本上只有一个where子句时,使用查询表达式毫无意义。

using System;using System.Linq;using System.Reflection;namespace Interfaces{    interface IFoo {}    interface IBar {}    interface IBaz {}}public class Test{    public static void CallMe<T>()    {        Console.WriteLine("typeof(T): {0}", typeof(T));    }    static void Main()    {        MethodInfo method = typeof(Test).GetMethod("CallMe");        var types = typeof(Test).Assembly.GetTypes()          .Where(t => t.Namespace == "Interfaces");        foreach (Type type in types)        { MethodInfo genericMethod = method.MakeGenericMethod(type); genericMethod.Invoke(null, null); // No target, no arguments        }    }}

原始答案

让我们忽略调用变量“接口”开始时的明显问题。

您必须通过反思来称呼它。泛型的重点是在 编译 时进行更多类型检查。您不知道编译时的类型是什么-因此必须使用泛型。

获取通用方法,并在其上调用MakeGenericMethod,然后调用它。

您的接口类型本身实际上是通用的吗?我问是因为您要在其上调用MakeGenericType,但没有传递任何类型参数…您是否要调用

Method<MyNamespace.Interface<string>>(); // (Or whatever instead of string)

要么

Method<MyNamespace.Interface>();

如果是后者,则只需要调用MakeGenericMethod-不需要MakeGenericType。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/416883.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号