gpt4 book ai didi

c# - 动态转换为通用接口(interface)

转载 作者:行者123 更新时间:2023-11-30 21:04:38 25 4
gpt4 key购买 nike

我有一个具有以下语法的外部函数:

public void Set<FieldType>(
Field field,
FieldType value
)

字段类型可以是一些原始类型,如intdoublebool等,也可以是这些类型的泛型列表,例如IList

问题是我必须准确传递一个IList< T > 接口(interface)。如果我传递任何实现 IList< T > 接口(interface)的类型,该函数将抛出 InvalidOperationException Unsupported type: System.Collections.Generic.List`1[[System.Int32 , mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

例如:

IList<int> list1 = new List<int>();
List<int> list2 = new List<int>();

Entity entity = new Entity();

//this works fine
entity.Set(field, list1);

//Here exception is throw
entity.Set(field, list2);

//works fine as well
entity.Set(field, list2 as IList<int>);

我通过反射动态获取列表的问题

var property = entityType.GetProperty(field.FieldName);
dynamic propertyValue = property.GetValue(myObject, null);

所以,propertyValue 是 List< T >,而不是 IList< T >,当我将这个值传递给外部函数时,我看到了一个异常。

很明显,是外部函数的bug。

我唯一的想法是将 propertyValue 转换为 IList< T >但我在编译时不知道 T

所以,我需要动态转换。我有一个像变量这样的通用列表接口(interface)类型

var genericIListType = typeof (IList<>)
.MakeGenericType(field.ValueType);

但是我找不到将 propertyValue 转换为这种类型的方法。我只能找到如何将对象转换为其他对象的示例(例如使用 Activator.CreateInstance),但我需要转换为接口(interface)。

请给我建议如何实现目标。

最佳答案

你可以包装外部函数:

public void SetWrapper<T>(Field field, List<T> list) {
entity.Set(field, (IList<T>)list);
}

关于c# - 动态转换为通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12245833/

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