调用热更工程里面的泛型方法
修改热更工程
在热更工程中添加泛型方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| using UnityEngine;
namespace HotFix { public class TestClass { private int m_Id; public int Id { get { return m_Id; } } public TestClass() { } public TestClass(int id) { m_Id = id;} public static void StaticFuncTest() { Debug.Log("Test"); } public static void StaticFuncTest2(int a) { Debug.Log("Test param a = " + a); }
public void GenericMethod<T>(T a) { Debug.Log("Test Generic a=" + a.ToString()); } } }
|
泛型方法调用
主要使用AppDomain.InvokeGenericMethod
这个API
修改ILRuntimeManager
的OnHotFixLoaded
方法
1 2 3 4 5 6 7 8 9 10 11 12
| void OnHotFixLoaded() { IType type = m_AppDomain.LoadedTypes["HotFix.TestClass"];
object obj2 = ((ILType)type).Instantiate();
IType stringType = m_AppDomain.GetType(typeof(string)); IType[] genericArgu = new IType[1] {stringType}; m_AppDomain.InvokeGenericMethod("HotFix.TestClass", "GenericMethod", genericArgu, obj2, "ATAO"); }
|
AppDomain.InvokeGenericMethod
有5个参数,第一个指定程序集和类名,第二个指定泛型方法名,第三个指定泛型类型的数组,第四个指定类的实例,第五个指定泛型方法的参数
泛型方法调用二
第二种调用方式和前面讲过的含参方法的第二种调用方式类似。
- 拿到泛型
IType
,把它放进一个IType数组里面
- 拿到参数
IType
,把它放进一个IType列表里面
- 拿到泛型方法,使用
IType.GetMethod
- 调用泛型方法,使用
AppDomain.Invoke
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| void OnHotFixLoaded() { IType type = m_AppDomain.LoadedTypes["HotFix.TestClass"];
object obj2 = ((ILType)type).Instantiate(); IType stringType = m_AppDomain.GetType(typeof(string)); IType[] genericArgu = new IType[1] {stringType}; List<IType> paramList = new List<IType>() { stringType }; IMethod method = type.GetMethod("GenericMethod", paramList, genericArgu); m_AppDomain.Invoke(method,obj2, "ATAO"); }
|
在这个示例中,泛型IType和参数IType都是AppDomain.GetType(typeof(string));