首页 / .NET / 正文

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

7240 1 发布于: 2018-01-15 读完约需8分钟

.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#中如何使用从流(stream)中创建一个字节数组(byte[])?

下一篇: .NET[C#]使用LINQ从List<T>集合中删除重复对象元素(去重)的方法有哪些?

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

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册