01.类型信息与泛型方法

[LuaCallCSharp]
static class ExtendedMethod
{
public static Rigidbody AddComponentRigidbody(this GameObject gameobject)
{
return gameobject.AddComponent<Rigidbody>();
}
}

Lua中通过调用扩展方法的方式来进行间接地调用

local go = CS.UnityEngine.GameObject("SuperCube")
go:AddComponentRigidbody();

或者
对于传入Type的第三种重载形式,xLua在Lua API中为我们提供了一个和C#中typeof函数一样的函数
在Lua代码中也可以通过typeof得到类的类型信息

local go = CS.UnityEngine.GameObject("SuperCube")
go:AddComponent(typeof(CS.UnityEngine.Rigidbody))
go:AddComponent(typeof(CS.UnityEngine.Animator))



类型转换
xLua为我们提供了一个类型转换函数cast,该函数有两个参数:
需要进行类型转换的对象
转换类型的Type对象(使用之前提到的typeof函数得到Type对象)

[LuaCallCSharp]
interface IFunkable
{

void Fuck();
}


[LuaCallCSharp]
public class Lisa : IFunkable
{
public int Coin=666;
private int id=100;
public void Fuck()
{
Debug.Log("Lisa[" + this.id + "] Can Fuck!");
}
}


[LuaCallCSharp]
class WhoerHouse
{
public IFunkable GetWhore()
{
return new Lisa();
}
}
--类型转换
local whoerHouse=CS.WhoerHouse();
local women=whoerHouse:GetWhore();
women:Fuck();
print(women.Coin);
--将得到的woman对象转换为IFuckable接口类型
cast(women,typeof(CS.IFunkable));
women:Fuck();
print(women.Coin);

09.XLua Lua访问C#中的方法_类型转换


其中IFuckable和WhoreHouse是该库对外暴露的接口,外部通过调用WhoreHouse的GetWhore方法来得到不同的实现了IFuckable接口的对象

在Lua代码中,我们通过GetWhore拿到了一个woman对象,但是由于不知道woman到底是哪一个具体的实现类,所以直接调用的时候xLua会通过反射的方式来访问该实现类

为了通过IFuckable接口来进行调用,需要在Lua中将得到的woman对象转换为IFuckable接口类型