设想:
我目前正在编写一个层来将 3 个类似的 Web 服务抽象为一个可用的类。每个 Web 服务都公开了一组具有共同性的对象。我创建了一组利用共性的中间对象。但是在我的层中,我需要在 Web 服务对象和我的对象之间进行转换。
在调用 Web 服务之前,我使用反射在运行时创建了适当的类型,如下所示:
public static object[] CreateProperties(Type type, IProperty[] properties)
{
//Empty so return null
if (properties==null || properties.Length == 0)
return null;
//Check the type is allowed
CheckPropertyTypes("CreateProperties(Type,IProperty[])",type);
//Convert the array of intermediary IProperty objects into
// the passed service type e.g. Service1.Property
object[] result = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
IProperty fromProp = properties[i];
object toProp = ReflectionUtility.CreateInstance(type, null);
ServiceUtils.CopyProperties(fromProp, toProp);
result[i] = toProp;
}
return result;
}
这是我的调用代码,来自我的一个服务实现:
Property[] props = (Property[])ObjectFactory.CreateProperties(typeof(Property), properties);
_service.SetProperties(folderItem.Path, props);
因此,每个服务都公开了一个不同的“Property”对象,我将其隐藏在我自己的 IProperty 接口实现后面。
反射代码在单元测试中工作,产生一个对象数组,其元素是适当的类型。但调用代码失败:
System.InvalidCastException:无法将“System.Object[]”类型的对象转换为“MyProject.Property[]”类型
有任何想法吗?
我的印象是,只要包含的对象是可转换的,来自 Object 的任何转换都会起作用?