.NET[C#]C#中如何使用反射调用泛型方法?

.NET 作者: Rector 43阅读 0评论 0收藏 收藏本文

郑重申明:本文未经许可,禁止任何形式转载

.NET[C#]C#中如何使用反射调用泛型方法?

问题摘要

比如有以下的包含泛型方法的类的代码片段:

public class Sample
{
    public void Example(string typeName)
    {
        Type myType = FindType(typeName);

        // 此处如何使用反射调用GenericMethod<T>()?
        GenericMethod<myType>(); // 这样做是不行的

        // 此处如何使用反射调用StaticMethod<T>()?
        Sample.StaticMethod<myType>(); // 这样做也是不行的
    }

    public void GenericMethod<T>()
    {
        // ...
    }

    public static void StaticMethod<T>()
    {
        //...
    }
}

示例一

MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);

示例二

var name = InvokeMemberName.Create;
Dynamic.InvokeMemberAction(this, name("GenericMethod", new[]{myType}));


var staticContext = InvokeContext.CreateStatic;
Dynamic.InvokeMemberAction(staticContext(typeof(Sample)), name("StaticMethod", new[]{myType}));

示例三

using System;
using System.Collections;
using System.Collections.Generic;

namespace DictionaryRuntime
{
    public class DynamicDictionaryFactory
    {
        /// <summary>
        /// Factory to create dynamically a generic Dictionary.
        /// </summary>
        public IDictionary CreateDynamicGenericInstance(Type keyType, Type valueType)
        {
            //Creating the Dictionary.
            Type typeDict = typeof(Dictionary<,>);

            //Creating KeyValue Type for Dictionary.
            Type[] typeArgs = { keyType, valueType };

            //Passing the Type and create Dictionary Type.
            Type genericType = typeDict.MakeGenericType(typeArgs);

            //Creating Instance for Dictionary<K,T>.
            IDictionary d = Activator.CreateInstance(genericType) as IDictionary;

            return d;

        }
    }
}

调用程序:

using System;
using System.Collections.Generic;

namespace DynamicDictionary
{
    class Test
    {
        static void Main(string[] args)
        {
            var factory = new DictionaryRuntime.DynamicDictionaryFactory();
            var dict = factory.CreateDynamicGenericInstance(typeof(String), typeof(int));

            var typedDict = dict as Dictionary<String, int>;

            if (typedDict != null)
            {
                Console.WriteLine("Dictionary<String, int>");

                typedDict.Add("One", 1);
                typedDict.Add("Two", 2);
                typedDict.Add("Three", 3);

                foreach(var kvp in typedDict)
                {
                    Console.WriteLine("\"" + kvp.Key + "\": " + kvp.Value);
                }
            }
            else
                Console.WriteLine("null");
        }
    }
}

输出:

Dictionary<String, int>
"One": 1
"Two": 2
"Three": 3

阅读了该文章的人还浏览了...

本文永久链接图享网 » .NET[C#]C#中如何使用反射调用泛型方法?

发布于: 2018-01-15 10:11:59
分享扩散:

文章评论

获取验证码