加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用泛型类中定义的泛型参数调用非泛型方法

发布时间:2020-12-15 08:44:23 所属栏目:百科 来源:网络整理
导读:这是我的问题; public class MyClassT{ public void DoSomething(T obj) { .... }} 我做的是: var classType = typeof(MyClass);Type[] classTypeArgs = { typeof(T) };var genericClass = classType.MakeGenericType(classTypeArgs);var classInstance = A
这是我的问题;
public class MyClass<T>
{
   public void DoSomething(T obj)
   {
      ....
   }
}

我做的是:

var classType = typeof(MyClass<>);
Type[] classTypeArgs = { typeof(T) };
var genericClass = classType.MakeGenericType(classTypeArgs);
var classInstance = Activator.CreateInstance(genericClass);
var method = classType.GetMethod("DoSomething",new[]{typeof(T)});
method.Invoke(classInstance,new[]{"Hello"});

在上面的例子中,我得到的异常是:无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作.

如果我尝试使方法通用,它会再次失败并出现异常:
MakeGenericMethod只能在MethodBase.IsGenericMethodDefinition为true的方法上调用.

我该如何调用该方法?

解决方法

您正在错误的对象上调用GetMethod.使用绑定的泛型类型调用它,它应该工作.这是一个完整的样本,它可以正常工作:
using System;
using System.Reflection;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        Type unboundGenericType = typeof(MyClass<>);
        Type boundGenericType = unboundGenericType.MakeGenericType(typeof(string));
        MethodInfo doSomethingMethod = boundGenericType.GetMethod("DoSomething");
        object instance = Activator.CreateInstance(boundGenericType);
        doSomethingMethod.Invoke(instance,new object[] { "Hello" });
    }

    private sealed class MyClass<T>
    {
        public void DoSomething(T obj)
        {
            Console.WriteLine(obj);
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读