gpt4 book ai didi

c# - 类型转换,Cast 的运行时替代方案?

转载 作者:行者123 更新时间:2023-11-30 21:03:28 26 4
gpt4 key购买 nike

我有一个 IList<object>其中每个对象都是类型的实例 T (我在编译时不知道)。

我需要一个 IList<T>出于这个。我不能使用 Cast,因为我在编译时不知道类型,而且没有我可以使用的 Cast(Type) 重载。

这是我目前拥有的:

private object Map(IList<ApiCallContext> bulk)
{
// god-awful way to build a IEnumerable<modelType> list out of Enumerable<object> where object is modelType.
// quoting lead: "think whatever you do it will be ugly"
Type modelType = model.Method.ModelType;

if (bulk.Count > 0)
{
modelType = bulk.First().Parameters.GetType();
}
Type listType = typeof(List<>).MakeGenericType(modelType);
object list = Activator.CreateInstance(listType);
foreach (object value in bulk.Select(r => r.Parameters))
{
((IList)list).Add(value);
}
return list;
}

我在想的是也许我可以创建一个新的 LooseList实现 IList 的类并且只是围绕 Actor 工作,似乎比我目前拥有的更好,但听起来仍然太笨重。

最佳答案

如果您真的需要完全按照您所说的去做,我会首先将其分为“特定于上下文的代码”和“可重用代码”。实际上你想要这样的东西:

public static IList ToStrongList(this IEnumerable source, Type targetType)

我将通过编写一个强类型方法然后通过反射调用它来实现:

private static readonly MethodInfo ToStrongListMethod = typeof(...)
.GetMethod("ToStrongListImpl", BindingFlags.Static | BindingFlags.NonPublic);

public static IList ToStrongList(this IEnumerable source, Type targetType)
{
var method = ToStrongListMethod.MakeGenericMethod(targetType);
return (IList) method.Invoke(null, new object[] { source });
}

private static List<T> ToStrongListImpl<T>(this IEnumerable source)
{
return source.Cast<T>().ToList();
}

关于c# - 类型转换,Cast<T> 的运行时替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12848673/

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