我有一個數據轉儲的exe文件。該exe會根據配置動態地選取DLL,並將類對象傳遞給它。該DLL具有與其一起編譯的此類的副本,並且可以在調試下看到數據,而不會將問題作爲對象。但是,當我嘗試將其轉換爲課程時,它會告訴我由於上下文無法進行。我確信我有時忽略了一些事情,因爲我有時會那樣做。InvalidCastException,錯誤的上下文?
錯誤:
[A]MyClass cannot be cast to [B]MyClass. Type A originates from 'MyExe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\MyPath\MyExe.exe'. Type B originates from 'MyDLL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location 'C:\MyPath\MyDLL.dll'.
EXE代碼:
Object[] param = new Object[] { MyClass };
MethodInfo m = type.GetMethod("MyMethod");
reader = (SqlDataReader)m.Invoke(obj, param);
DLL代碼:
public SqlDataReader MyMethod(Object param)
{
SqlDataReader reader = new SqlDataReader();
Type t = param.GetType(); //Returns MyClass
if (param is MyClass) //Returns false
reportItem = (MyClass)param; //Never executes
MyClass reportItem = (MyClass)param; //InvalidCastException
//other code here, pulling data
return reader;
}
我的猜測是你必須動態地創建你傳入的類對象作爲參數。或者在MyMethod中,使用傳入對象的屬性創建一個新的MyClass。 – 2013-03-14 14:53:59