C#中记录一下使用字符串文本调用泛型方法

C#是静态类型语言,泛型参数在编译时必须确定,不能直接使用一个字符串来指定泛型参数,可以通过反射或者缓存打开窗口的委托来调用泛型方法。​​​​​​​​​​​​​​​​​​​​​​​​​​​​

准备:

准备几个测试供后续使用,代码如下:

cs 复制代码
public class Animal
{
    public virtual void Print()
    {

    }
}

public class Dog : Animal
{
    public override void Print() 
    {
        Debug.Log("这是一只狗");
    }
}

public class Duck : Animal
{
    public override void Print()
    {
        Debug.Log("这是一只鸭子");
    }
}

public class Test : MonoBehaviour
{
    void Start()
    {

    }
    
    public void SummonAnimal<T>() where T : Animal,new()
    {
        T animal = new T();
        animal.Print();
    }
}

方案一:

代码如下:

cs 复制代码
   public void CallAnimalByName(string animalClassName)
   {
       // 获取程序集中的类型
       var type = Assembly.GetExecutingAssembly()
           .GetTypes()
           .FirstOrDefault(t => t.Name == animalClassName &&
                               t.IsSubclassOf(typeof(Animal)));

       if (type != null)
       {
           // 通过反射调用泛型方法
           var method = typeof(Test).GetMethod("SummonAnimal");
           var genericMethod = method.MakeGenericMethod(type);
           genericMethod.Invoke(this, null);
       }
   }

在Test的Start方法中调用

cs 复制代码
    void Start()
    {
        CallAnimalByName("Dog");
    }

结果:

方案二:

代码如下:

cs 复制代码
    private Dictionary<string, Action> animalActions = new Dictionary<string, Action>();

    // 注册窗口类型
    public void RegisterWindow<T>() where T : Animal, new()
    {
        string animalName = typeof(T).Name;
        animalActions[animalName] = () => SummonAnimal<T>();
    }

    // 通过配置调用
    public void CallAnimalByName2(string animalName)
    {
        if (animalActions.TryGetValue(animalName, out Action action))
        {
            action();
        }
    }

在Test的Start方法中调用:

cs 复制代码
void Start()
{
   RegisterWindow<Duck>();
   CallAnimalByName2("Duck");
}

结果:​​​​​​​

相关推荐
.房东的猫16 小时前
ERP(金蝶云星空)开发【安装篇】
c#
fie88891 天前
基于C#的推箱子小游戏实现
开发语言·c#
.房东的猫1 天前
ERP(金蝶云星空)开发【业务数据中心创建和注册】
c#
bugcome_com1 天前
C# 进阶核心知识点汇总|多项目开发 + 委托 + Lambda + 事件一次吃透
c#
SunflowerCoder1 天前
基于插件化 + Scriban 模板引擎的高效 HTTP 协议中心设计
http·c#
青云计划1 天前
知光项目用户关系模块
c#·linq
m5655bj1 天前
使用 C# 修改 PDF 页面尺寸
java·pdf·c#
专注VB编程开发20年1 天前
c#模仿内置 Socket.Receive(无需 out/ref,直接写回数据)
开发语言·c#
bugcome_com1 天前
【零基础入门】C# 核心教程:从 HelloWorld 到入门精髓
c#
JQLvopkk1 天前
C# 实现Http Json格式 Post 、Get 方法请求 winform服务器
http·c#·json