方案:無法將'System.Object []'類型的對象轉換爲'MyObject []',給出了什麼?
我目前正在編寫一個圖層,將3個類似的webservices抽象爲一個可用的類。每個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的強制轉換都可以工作。
那麼,要迂腐,Object [] *是*一個對象...所以演員陣容並不奇怪。一切都是.NET中的一個對象 – 2008-10-17 14:50:17