59 lines
1.4 KiB
C#
59 lines
1.4 KiB
C#
using System;
|
|
using UnityEditor;
|
|
using UnityEngine;
|
|
|
|
|
|
namespace Blocks4u.Runtime
|
|
{
|
|
[InitializeOnLoad]
|
|
public static class CastUtility
|
|
{
|
|
//TODO cast anything to anything
|
|
|
|
public static T Cast<T>(object anything)
|
|
{
|
|
var targetType = typeof(T);
|
|
if (anything is T target)
|
|
{
|
|
return target;
|
|
}
|
|
|
|
if (targetType == typeof(string))
|
|
{
|
|
return (T) (object) (anything.ToString());
|
|
}
|
|
|
|
if (targetType == typeof(float))
|
|
{
|
|
var t = (float) (int) anything;
|
|
return (T) (object) t;
|
|
}
|
|
|
|
if (IsNumericType(targetType) && IsNumericType(anything.GetType()))
|
|
{
|
|
// ReSharper disable once PossibleInvalidCastException
|
|
return (T) anything;
|
|
}
|
|
|
|
|
|
|
|
return (T) anything;
|
|
|
|
throw new InvalidCastException($"Cannot cast object of type {anything.GetType()} to type {typeof(T)}");
|
|
}
|
|
|
|
public static bool IsNumericType(Type type)
|
|
{
|
|
return type.IsAssignableFrom(typeof(IConvertible)) && type.IsAssignableFrom(typeof(IComparable));
|
|
}
|
|
|
|
static CastUtility()
|
|
{
|
|
object kek = 123;
|
|
|
|
var jabba = Cast<float>(kek);
|
|
|
|
Debug.LogError(jabba);
|
|
}
|
|
}
|
|
} |