gpt4 book ai didi

c# - 将 object[] 类型转换为泛型类型 K,它也是一个数组

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:04 26 4
gpt4 key购买 nike

我尝试编写一个适用于复杂对象和对象数组的通用类型转换方法。下面是我的代码:

public void Test()
{
MyClass2[] t2 = m.MapItem<MyClass1[], MyClass2[]>(t1);
return;
}

public K MapItem<T, K>(T source)
{
if (typeof(T).IsArray && typeof(K).IsArray)
{
Type ek = typeof(K).GetElementType();
IList sourceList = (IList)source;
List<object> tmp = new List<object>();
for (int i = 0; i < sourceList.Count; i++)
{
var k = Activator.CreateInstance(ek);
tmp.Add(k);
}
var resultObj = tmp.ToArray();
MapItem(source, resultObj);

//Here i have resultObj is an object[] of the results,
//which is to be casted result type K
//BUT DOES NOT WORK!!!
return (K)Convert.ChangeType(resultObj, typeof(K));

}
else
{
MethodInfo myMapperMethod = GetMyMapperMethodForThisType(typeof(T), typeof(K));
return (K)myMapperMethod.Invoke(null, new object[] { source });
}
}

public K MapItem<T, K>(T source, K dest)
{
if (typeof(T).IsArray && typeof(K).IsArray)
{
IList sourceList = (IList)source;
IList destList = (IList)dest;
for (int i = 0; i < sourceList.Count; i++)
{
MapItem(sourceList[i], destList[i]);
}
return dest;
}
else
{
MethodInfo myMapperMethod = GetMyMapperMethodForThisType(typeof(T),typeof(K));
return (K) myMapperMethod.Invoke(null, new object[] { source, dest });
}
}

private MethodInfo GetMyMapperMethodForThisType(Type type1, Type type2)
{
//some code to find appropriate function...
}

但是,return (K) Convert.ChangeType(y, typeof(K)); 无法从 object[] 转换为 K .我如何执行此转换以从 object[] 返回 K

注意:json 序列化有效,但我不想使用反射或序列化。

  string jsonStr = JsonConvert.SerializeObject(resultObj);
return JsonConvert.DeserializeObject<K>(jsonStr);

最佳答案

基本上我认为你想避免使用 List<object>根本。您应该只创建大小合适的数组:

IList dest = Array.CreateInstance(ek, sourceList.Count);
for (int i = 0; i < sourceList.Count; i++)
{
dest[i] = Activator.CreateInstance(ek);
}
K result = (K) dest;
// Note that this is calling MapItem<T, K>, not MapItem<T, object[]>
MapItem(source, result);
return result;

关于c# - 将 object[] 类型转换为泛型类型 K,它也是一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24649156/

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