调用 ImmutableArray<T> Create<T>(params T[]? items) 动态给定类型为 T[] 的对象

问题描述 投票:0回答:1

我正在尝试调用创建一个不可变数组,给定一个

object
变量,该变量实际上具有
T[]
类型。如何使用反射来做到这一点。问题是
ImmutableArray.Create
有很多重载,我得到了一个不明确的方法异常。

var method = typeof(ImmutableArray).GetMethod(nameof(ImmutableArray.Create)).Invoke(null, arr);
c# .net-core reflection
1个回答
0
投票

这就是我解决寻找

ImmutableArray<T> Create<T>(params T[]? items)
方法并在给定数组的情况下调用它的问题的方法。

var method = typeof(ImmutableArray)
  .GetMethods()
  .Where(m => m is { Name: nameof(ImmutableArray.Create), IsPublic: true, IsGenericMethod: true })
  .Single(m => m.GetParameters().Length == 1 &&
              m.GetParameters()[0].GetCustomAttribute<ParamArrayAttribute>() != null &&
              m.GetParameters()[0].ParameterType is { IsArray: true });

var immutableArrayCreateMethodInfo = method.MakeGenericMethod(arr.GetType());

immutableArrayCreateMethodInfo.Invoke(null, new[] { arr });
© www.soinside.com 2019 - 2024. All rights reserved.