Well, I do not entirely understand the following, but it seems to work for both .NET and Mono and it doesn't allocate. Any comments on caveats or reliability would be appreciated!
This was adapted from here (the only difference is that Expression.Parameter
requires a second parameter to please the version of Mono which is used by Unity.
internal static class CastTo<T> {
public static T From<S>(S s) {
return Cache<S>.caster(s);
}
static class Cache<S> {
internal static readonly Func<S, T> caster = Get();
static Func<S, T> Get() {
var p = Expression.Parameter(typeof(S), "S");
var c = Expression.ConvertChecked(p, typeof(T));
return Expression.Lambda<Func<S, T>>(c, p).Compile();
}
}
}
Which can then be used as follows:
public enum Example {
A,
B,
C,
}
long example = CastTo<long>.From<Example>(Example.B);