如何动态分配通用类型 [英] How to dynamically assign generic Type

查看:121
本文介绍了如何动态分配通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通用类:

Generic class:

public class GenericEntityMapping
{
    public T Map<t>(XmlNode xNode, T entityObject)
    {
        //FYI.
        //PropertyInfo[] entityProperties = typeof(T).GetProperties();
        //foreach (PropertyInfo pInfo in entityProperties){...}

        //somewhere in the code depends on the condition.
        if true then...
        GenericEntityMapping<SampleEntity01>.Map(node, new SampleEntity01())
        .
        .
        .
        else if true then...
        GenericEntityMapping<SampleEntity02>.Map(node, new SampleEntity02())
    }
}




在通用类型不需要硬编码的情况下,我该怎么办?


我的目标是这样的:
类型myType = pInfo.PropertyType.GetType();
GenericEntityMapping< myType> .Map(node,System.Activator.CreateInstance< myType>());




How can i do it where the type in the generic needs not to be hardcoded?


My goal is something like:
Type myType = pInfo.PropertyType.GetType();
GenericEntityMapping<myType>.Map(node, System.Activator.CreateInstance<myType>());

Is it possible?

推荐答案

对于类型,泛型和开始静态不相关.泛型和非泛型类型都可以是静态的,也可以不是静态的.

—SA
For a type, being generic and begin static are not related. Both generic and non-generic types can be static or not static.

—SA


你好SAKryukov,
感谢您的快速回复.

我找到了解决方法:

Hello SAKryukov,
Thanks for the quick reply.

I found the solution:

MethodInfo method = typeof(GenericEntityMapping).GetMethod("Map");
MethodInfo generic = method.MakeGenericMethod(Type.GetType(pInfo.PropertyType.FullName));

object[] objParam = { node, System.Activator.CreateInstance(Type.GetType(pInfo.PropertyType.FullName)) };
pInfo.SetValue(entity, generic.Invoke(this, objParam), null);


这篇关于如何动态分配通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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