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

问题描述

通用类:

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?

推荐答案


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);


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

08-01 00:43