2023-06-29 14:57:11 +08:00
|
|
|
using System;
|
2024-06-13 16:02:49 +08:00
|
|
|
using System.Collections;
|
|
|
|
using System.Linq;
|
2023-06-29 14:57:11 +08:00
|
|
|
|
|
|
|
namespace BITKit
|
|
|
|
{
|
|
|
|
public static class MathO
|
|
|
|
{
|
2024-06-13 16:02:49 +08:00
|
|
|
public static T As<T>(this object self)
|
2024-06-12 16:01:56 +08:00
|
|
|
{
|
2024-06-12 16:49:42 +08:00
|
|
|
// {
|
|
|
|
// 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;
|
|
|
|
// }
|
|
|
|
// }
|
2024-06-13 16:02:49 +08:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2024-06-12 16:01:56 +08:00
|
|
|
}
|
2023-06-29 14:57:11 +08:00
|
|
|
}
|
|
|
|
}
|