在运行时间确定在非泛型类泛型类型 [英] Determining a Generic Type at Runtime in Non-Generic Class

查看:139
本文介绍了在运行时间确定在非泛型类泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经得到了我自己处于困境之中,并且可以使用一个大师的帮助下...

I've gotten myself in a pickle, and could use the help of a guru...

我有一个杂志,记录条目不同的类型:

I have a Journal that records entries for different types:

Journal(Of ParentT)

- 家长可以客户地址,其他类

杂志的构造函数需要的类型参数的知识:

The constructor of the Journal requires knowledge of the Type parameter:

Public Sub New(Parent as ParentT)

在我的消费形式,我把日记在构造函数中:

In my consuming form, I take a Journal in the constructor:

Public Sub DisplayForm(Journal as object)

在这一点上,我也不能确定是什么类型的杂志是。我已经看过了使用反射与的MethodInfo > MakeGenericMethod DynamicMethod的,代表等,但还没有找到一个可行的解决方案。

At this point, I cannot determine what type the Journal is for. I have looked at using Reflection with the MethodInfo > MakeGenericMethod, DynamicMethod, delegates, etc, but haven't found a workable solution.

我愿意考虑在这一点上几乎所有的选择......

I am willing to consider most any option at this point...

推荐答案

我可能误解了这个问题,但如果我理解正确的话,杂志,其实是一个通用类与泛型参数 ParentT ;这仅仅是参考一杂志< ParentT> 实例的非通用 System.Object的键入。在这种情况下,下面的方法应该很好地工作:

I may have misunderstood the question, but if I understand correctly, Journal is in fact a generic class with generic parameter ParentT; it is only that the reference to a Journal<ParentT> instance is of the non-generic System.Object type. In this case, the following method should work fine:

System.Type.GetGenericArguments

对不起,这code是在C#中,但:

Sorry that this code is in C#, but:

 object obj = new List<int>();
 Console.WriteLine(obj.GetType().GetGenericArguments().First().ToString());

输出:

System.Int32

在你的情况,你可能想是这样的:

In your case, you might want something like:

Type journalGenericType = myJournal.GetType().GetGenericArguments().First();

if (journalGenericType == typeof(Customer))
{
    ...
}
else 
{
    ...
}

这篇关于在运行时间确定在非泛型类泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆