前言
我们继续来一起看下ILRuntime的第四个案例———Inheritance:继承。 这一篇主要讲的是ILRuntime的继承问题,如果是全部在热更工程中的继承,用法跟普通继承是一样的。如果你想在热更DLL项目当中继承一个Unity主工程里的类,或者实现一个主工程里的接口,这就是禁停啊要讲的跨域继承,你需要在Unity主工程中实现一个继承适配器。这是这一系列文章的总目录链接
🏺有疑问的可以先看下之前的文章。
一、继承分类
在ILRuntime中,存在两种继承,一种就是普通的继承,和平时的继承的用法一样,这里我们着重的介绍下第二种继承,跨域继承,因为unity工程和热更工程处于两个不同的程序域,是无法直接进行代码互通的。所以需要去跨域继承。
二、跨域继承的用法
在热更工程中,找到TestInheritance.cs,这里面就是跨域继承了,内容为重写了几个基类的方法。
//一定要特别注意,:后面只允许有1个Unity主工程的类或者接口,但是可以有随便多少个热更DLL中的接口
public class TestInheritance : TestClassBase
{
public override int Value { get; set; }
public override void TestAbstract(int gg)
{
UnityEngine.Debug.Log("!! TestInheritance.TestAbstract gg =" + gg);
}
public override void TestVirtual(string str)
{
base.TestVirtual(str);
UnityEngine.Debug.Log("!! TestInheritance.TestVirtual str =" + str);
}
public static TestInheritance NewObject()
{
return new HotFix_Project.TestInheritance();
}
}
1.继承适配器
之前的操作和以前几个案例都一样,创建程序域啥的,就不一一解释了。
需要在unity工程中去写继承适配器,用于跨域继承
在Inheritance.cs这个脚本中,写了个基类,用于继承
public abstract class TestClassBase
{
public virtual int Value
{
get
{
return 0;
}
set
{
}
}
public virtual void TestVirtual(string str)
{
Debug.Log("!! TestClassBase.TestVirtual, str = " + str);
}
public abstract void TestAbstract(int gg);
}
创建继承适配器
void OnHotFixLoaded()
{
Debug.Log("首先我们来创建热更里的类实例");
TestClassBase obj;
Debug.Log("现在我们来注册适配器, 该适配器由ILRuntime/Generate Cross Binding Adapter菜单命令自动生成");
appdomain.RegisterCrossBindingAdaptor(new TestClassBaseAdapter());
Debug.Log("现在再来尝试创建一个实例");
obj = appdomain.Instantiate<TestClassBase>("HotFix_Project.TestInheritance");
Debug.Log("现在来调用成员方法");
obj.TestAbstract(123);
obj.TestVirtual("Hello");
obj.Value = 233;
Debug.LogFormat("obj.Value={0}", obj.Value);
Debug.Log("现在换个方式创建实例");
obj = appdomain.Invoke("HotFix_Project.TestInheritance", "NewObject", null, null) as TestClassBase;
obj.TestAbstract(456);
obj.TestVirtual("Foobar");
obj.Value = 2333333;
Debug.LogFormat("obj.Value={0}", obj.Value);
}
最主要的就是这行代码
appdomain.RegisterCrossBindingAdaptor(new TestClassBaseAdapter());
2.实际应用
在创建完继承适配器之后,需要创建实例,然后再来调用
案例中列举了两种创建实例的方法
1.obj = appdomain.Instantiate<TestClassBase>("HotFix_Project.TestInheritance");
2.obj = appdomain.Invoke("HotFix_Project.TestInheritance", "NewObject", null, null) as TestClassBase;
接下就是调用了
然后我们来看下最后运行后的结果
总结
欢迎大佬多多来给萌新指正,欢迎大家来共同探讨。
如果各位看官觉得文章有点点帮助,跪求各位给点个“一键三连”,谢啦~
声明:本博文章若非特殊注明皆为原创原文链接
https://blog.csdn.net/Wrinkle2017/article/details/120653828
————————————————————————————————
💢💢版权声明
版权声明:本博客为非营利性个人原创
所刊登的所有作品的著作权均为本人所拥有
本人保留所有法定权利,违者必究!
对于需要复制、转载、链接和传播博客文章或内容的
请及时和本博主进行联系
对于经本博主明确授权和许可使用文章及内容的
使用时请注明文章或内容出处并注明网址
转载请附上原文出处链接及本声明