Add more objects types checks and casting utilities to ScriptingObject

This commit is contained in:
Wojtek Figat
2020-12-21 14:03:15 +01:00
parent 3a314d97eb
commit 585c752d72
2 changed files with 32 additions and 4 deletions

View File

@@ -72,6 +72,12 @@ ScriptingObject* ScriptingObject::ToNative(MonoObject* obj)
return ptr; return ptr;
} }
bool ScriptingObject::Is(const ScriptingTypeHandle& type) const
{
CHECK_RETURN(type, false);
return _type == type || CanCast(GetClass(), type.GetType().ManagedClass);
}
void ScriptingObject::ChangeID(const Guid& newId) void ScriptingObject::ChangeID(const Guid& newId)
{ {
ASSERT(newId.IsValid() && newId != _id); ASSERT(newId.IsValid() && newId != _id);
@@ -206,6 +212,14 @@ void ScriptingObject::UnregisterObject()
Scripting::UnregisterObject(this); Scripting::UnregisterObject(this);
} }
bool ScriptingObject::CanCast(const ScriptingTypeHandle& from, const ScriptingTypeHandle& to)
{
if (!from && !to)
return true;
CHECK_RETURN(from && to, false);
return CanCast(from.GetType().ManagedClass, to.GetType().ManagedClass);
}
bool ScriptingObject::CanCast(MClass* from, MClass* to) bool ScriptingObject::CanCast(MClass* from, MClass* to)
{ {
if (!from && !to) if (!from && !to)

View File

@@ -131,12 +131,30 @@ public:
return obj ? obj->GetOrCreateManagedInstance() : nullptr; return obj ? obj->GetOrCreateManagedInstance() : nullptr;
} }
/// <summary>
/// Checks if can cast one scripting object type into another type.
/// </summary>
/// <param name="from">The object type for the cast.</param>
/// <param name="to">The destination type to the cast.</param>
/// <returns>True if can, otherwise false.</returns>
static bool CanCast(const ScriptingTypeHandle& from, const ScriptingTypeHandle& to);
/// <summary>
/// Checks if can cast one scripting object type into another type.
/// </summary>
/// <param name="from">The object class for the cast.</param>
/// <param name="to">The destination class to the cast.</param>
/// <returns>True if can, otherwise false.</returns>
static bool CanCast(MClass* from, MClass* to);
template<typename T> template<typename T>
static T* Cast(ScriptingObject* obj) static T* Cast(ScriptingObject* obj)
{ {
return obj && CanCast(obj->GetClass(), T::GetStaticClass()) ? (T*)obj : nullptr; return obj && CanCast(obj->GetClass(), T::GetStaticClass()) ? (T*)obj : nullptr;
} }
bool Is(const ScriptingTypeHandle& type) const;
bool Is(MClass* type) const bool Is(MClass* type) const
{ {
return CanCast(GetClass(), type); return CanCast(GetClass(), type);
@@ -185,10 +203,6 @@ public:
/// </summary> /// </summary>
void UnregisterObject(); void UnregisterObject();
private:
static bool CanCast(MClass* from, MClass* to);
protected: protected:
/// <summary> /// <summary>