Net.Like.Xue.Tokyo/Assets/BITKit/Core/Mathematics/MathO.cs

49 lines
1.3 KiB
C#

using System;
using System.Collections;
using System.Linq;
namespace BITKit
{
public static class MathO
{
public static T As<T>(this object self)
{
// {
// if (typeof(T) == typeof(object[]))
// {
// var o = new object[1];
// o[0] = self;
// return o as T;
// }
// }
// {
// if (self is object[] { Length: 1 } o)
// {
// return o[0] as T;
// }
// }
try
{
return (T)self;
}
catch (InvalidCastException)
{
if(self.GetType().IsArray && typeof(T).IsArray && self is IEnumerable enumerable)
{
var newArray = Array.CreateInstance(typeof(T).GetElementType()!, enumerable.Cast<object>().Count());
var i = 0;
foreach (var x in enumerable)
{
newArray.SetValue(x, i++);
}
if (newArray is T newValue)
{
return newValue;
}
}
throw;
}
}
}
}