c# .NET 6.0 当您只有基础对象时,确定用于 Func<T> 的泛型类型
c# .NET 6.0 Determine the generic type used for a Func<T> when all you have is the base object
假设我们有一个将常规对象作为参数的方法。我需要测试该对象是否为 Func,调用它并检索 return 值,但泛型类型可以是任何类型,我无法列出一长串可能性:
public static object? Process(object o, out Type? type)
{
type = null;
if (o is Action action) action();
else if (o is int i) { type = typeof(long); return (long)i * (long)i; }
else if (o is double d) { type = typeof(float); return (float)(d - (long)d); }
else if (o is Func<int> funcint) { type = typeof(int); return funcint(); }
else if (o is Func<string> funcstr) { type = typeof(string); return funcstr(); }
else if (o is Func<object> funcobj) { type = typeof(object); return funcobj(); }
// ...
// ...
return null;
}
您可以通过反射获取参数类型,然后将 Func
转换为 `Delegate
Type t = o.GetType();
if (t.GetGenericTypeDefinition() == typeof(Func<>)
&& t.GetGenericArguments().Length == 1)
{
type = t.GetGenericArguments()[0];
return ((Delegate)o).DynamicInvoke();
}
假设我们有一个将常规对象作为参数的方法。我需要测试该对象是否为 Func,调用它并检索 return 值,但泛型类型可以是任何类型,我无法列出一长串可能性:
public static object? Process(object o, out Type? type)
{
type = null;
if (o is Action action) action();
else if (o is int i) { type = typeof(long); return (long)i * (long)i; }
else if (o is double d) { type = typeof(float); return (float)(d - (long)d); }
else if (o is Func<int> funcint) { type = typeof(int); return funcint(); }
else if (o is Func<string> funcstr) { type = typeof(string); return funcstr(); }
else if (o is Func<object> funcobj) { type = typeof(object); return funcobj(); }
// ...
// ...
return null;
}
您可以通过反射获取参数类型,然后将 Func
转换为 `Delegate
Type t = o.GetType();
if (t.GetGenericTypeDefinition() == typeof(Func<>)
&& t.GetGenericArguments().Length == 1)
{
type = t.GetGenericArguments()[0];
return ((Delegate)o).DynamicInvoke();
}