This commit is contained in:
CortexCore
2024-06-13 16:02:49 +08:00
parent ceea55b67a
commit 4a2ab82e20
4 changed files with 57 additions and 35 deletions

View File

@@ -1,10 +1,12 @@
using System;
using System.Collections;
using System.Linq;
namespace BITKit
{
public static class MathO
{
public static T As<T>(this object self) where T : class
public static T As<T>(this object self)
{
// {
// if (typeof(T) == typeof(object[]))
@@ -20,7 +22,28 @@ namespace BITKit
// return o[0] as T;
// }
// }
return self 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;
}
}
}
}