【问题标题】:Passed an instantiated System.Type as a Type Parameter for a Generic method将实例化的 System.Type 作为通用方法的类型参数传递
【发布时间】:2010-10-06 08:28:41
【问题描述】:

我有这个代码 sn-p 我想简化:

        switch (typeString)
        {
            case "boolean":
                CreateSimpleRows<bool>(ref group, value);
                break;
            case "datetime":
                CreateSimpleRows<DateTime>(ref group, value);
                break;
            case "double":
                CreateSimpleRows<double>(ref group, value);
                break;
            case "int32":
                CreateSimpleRows<int>(ref group, value);
                break;
            case "int64":
                CreateSimpleRows<long>(ref group, value);
                break;
            case "string":
                CreateSimpleRows<string>(ref group, value);
                break;
        }

方法被声明为CreateSimpleRows&lt;T&gt;。我尝试传递一个 System.Type 实例,但没有成功。

我遇到了一个类似问题的答案: Pass An Instantiated System.Type as a Type Parameter for a Generic Class

我检查过,发现 MethodInfo 类中有一个 MakeGenericMethod。 问题是,我不知道如何将“CreateSimpleRows”转换为 MethodInfo 实例。

我想实现的目标有可能吗? 提前感谢您的回复。

【问题讨论】:

  • 当然这很酷,如果你的目标是“简化”我会远离反思。
  • @jdv 是的,现在使用反射破坏了我简化的意图,这让我很震惊。感谢您指出这一点。

标签: reflection c#-3.0 c#-2.0 generics


【解决方案1】:

要获得MethodInfo,请致电Type.GetMethod:

MethodInfo method = typeof(TypeContainingMethod).GetMethod("CreateSimpleRows");
MethodInfo generic = method.MakeGenericMethod(typeArgument);

请注意,如果您想获得一个非公共方法,您需要使用 GetMethod 的重载,它也需要一个 BindingFlags。

目前还不清楚为什么要通过反射来做到这一点。虽然您当前的 sn-p 是重复的,但至少易于理解。使用反射可能会使事情更容易出错,并且您仍然必须将 typeString 映射到 Type 才能开始。

【讨论】:

  • 我明白了。我猜我最初的意图是删除代码的重复部分。看到您对类似问题的回答让我希望这是可能的。我现在才想到使用反射实际上违背了我的初衷。感谢您的快速回复! :)
猜你喜欢
  • 2010-09-20
  • 2022-01-05
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 2019-03-26
  • 2020-01-26
相关资源
最近更新 更多