gpt4 book ai didi

c# - 一种通过参数计数动态获取通用 Action<> 类型的更优雅的方法?

转载 作者:太空狗 更新时间:2023-10-29 18:20:20 25 4
gpt4 key购买 nike

目前我正在这样做(//编辑:这完全是愚蠢的,因为有一个数组,它以我昨天做我的字典的相同方式对它的项目进行编号):

    Dictionary<int, Type> genericMap = new Dictionary<int, Type>
{
{ 0, typeof(Action) },
{ 1, typeof(Action<>) },
{ 2, typeof(Action<,>) },
{ 3, typeof(Action<,,>) },
{ 4, typeof(Action<,,,>) },
{ 5, typeof(Action<,,,,>) },
{ 6, typeof(Action<,,,,,>) },
{ 7, typeof(Action<,,,,,,>) },
{ 8, typeof(Action<,,,,,,,>) },
};

还有别的地方...

var parms = meth.GetParameters();
dType = genericMap[parms.Length].MakeGenericType(parms.Select(p => p.ParameterType).ToArray());

其中 meth 是 MethodInfo。

有没有更优雅的方式来做到这一点?或者我是否必须定义这样的映射才能动态获取与参数计数对应的正确 Action<> 类型?

最佳答案

编辑:

顺便说一句,你知道Expression.GetActionType吗? ?

Creates a Type object that represents a generic System.Action delegate type that has specific type arguments.

使用该方法,您可以:

dType = Expression.GetActionType( parms.Select(p => p.ParameterType).ToArray() );

其他方式:

var parms = meth.GetParameters();

int numArgs = parms.Length;

if(numArgs == 0)
{
dType = typeof(Action);
}
else
{
var rawType = Type.GetType("System.Action`" + numArgs);
dType = rawType.MakeGenericType(parms.Select(p => p.ParameterType).ToArray());
}

但是您的方法确实没有任何问题;就反射(reflection)而言,尽可能明确通常是更好的选择。

此外,还有另一种构建 map 的奇特方法:

typeof(Action).Assembly
.GetExportedTypes()
.Where(type => type.FullName.StartsWith("System.Action")
&& type.IsSubclassOf(typeof(Delegate)))
.ToDictionary(type => type.GetGenericArguments().Length)

关于c# - 一种通过参数计数动态获取通用 Action<> 类型的更优雅的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15851452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com