【问题标题】:Using a string value as a generic type parameter [duplicate]使用字符串值作为泛型类型参数
【发布时间】:2019-11-01 10:10:31
【问题描述】:

假设我有一个看起来像这样的方法:

public bool Execute<T>()
 {
 }

...我有一个字符串变量,描述了我需要传入的类型的类名,比如

string typeName = "Person"

我天真地尝试过

var typeDef = Type.GetType(typeName);
 Execute<typeDef>();

,但这是不行的。当我只有字符串中的类名时,是否有一种编程方式来传递泛型类型参数?

【问题讨论】:

    标签: c# .net system.reflection


    【解决方案1】:
    var typeDef = Type.GetType(typeName);
    var ret = (bool)this.GetType().GetMethod(nameof(Execute)).MakeGenericMethod(typeDef).Invoke(this, new object[0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 2021-04-28
      • 2021-09-23
      • 1970-01-01
      相关资源
      最近更新 更多