目前我正在这样做(//编辑:这是完全愚蠢的,因为有一个数组,因此与我昨天的词典相同的方式对其项目进行编号):
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<,,,,,,,>) },
};
Run Code Online (Sandbox Code Playgroud)
而在其他地方......
var parms = meth.GetParameters();
dType = genericMap[parms.Length].MakeGenericType(parms.Select(p => p.ParameterType).ToArray());
Run Code Online (Sandbox Code Playgroud)
其中meth是MethodInfo.
有更优雅的方式吗?或者我是否必须定义这样的映射以动态获取与参数计数对应的正确Action <>类型?
Ani*_*Ani 12
编辑:
顺便说一句,你知道Expression.GetActionType吗?
创建一个Type对象,该对象表示具有特定类型参数的通用System.Action委托类型.
使用该方法,您可以:
dType = Expression.GetActionType( parms.Select(p => p.ParameterType).ToArray() );
Run Code Online (Sandbox Code Playgroud)
其他方法:
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());
}
Run Code Online (Sandbox Code Playgroud)
但是你的方法真的没有错; 当涉及到反思时,尽可能明确表达通常是更好的选择.
此外,这是构建地图的另一种奇特方式:
typeof(Action).Assembly
.GetExportedTypes()
.Where(type => type.FullName.StartsWith("System.Action")
&& type.IsSubclassOf(typeof(Delegate)))
.ToDictionary(type => type.GetGenericArguments().Length)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1914 次 |
| 最近记录: |