传递实例化的 System.Type 作为泛型方法的类型参数
我有一个想要简化的代码片段:
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
。我尝试传递 System.Type 实例,但这不起作用。
我在类似问题上找到了这个答案: 传递将 System.Type 实例化为泛型类的类型参数
我检查过,发现 MethodInfo 类中有一个 MakeGenericMethod。 问题是,我不知道如何将“CreateSimpleRows”转换为 MethodInfo 实例。
我想要实现的目标是否可能实现? 预先感谢您的回复。
I have this code snippet that I want to simplify:
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;
}
The method is declared as CreateSimpleRows<T>
. I tried passing a System.Type instance, but that didn't work.
I came across this answer to a similar question:
Pass An Instantiated System.Type as a Type Parameter for a Generic Class
I've checked and I've seen that there's a MakeGenericMethod in the MethodInfo class.
Thing is, I don't know how to convert "CreateSimpleRows" into a MethodInfo instance.
Is what I'm thinking of achieving even possible?
Thanks in advance for the replies.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要获取
MethodInfo
,请调用 < code>Type.GetMethod:请注意,如果您想获取非公共方法,则需要使用
GetMethod
的重载,该重载采用BindingFlags
也是如此。不过,目前还不清楚为什么要通过反思来做到这一点。虽然您当前的代码片段是重复的,但至少很容易理解。使用反射可能会使事情更容易出错,并且您仍然必须首先将
typeString
映射到Type
。To get a
MethodInfo
, you callType.GetMethod
:Note that if you want to get a non-public method you'll need to use the overload of
GetMethod
which takes aBindingFlags
as well.It's not really clear why you want to do this with reflection though. While your current snippet is repetitive, it's at least simple to understand. Using reflection is likely to make things more error-prone, and you'd still have to map
typeString
to aType
to start with.