我正在嘗試調用類RFIDeas_Wrapper
(正在使用dll)中定義的函數。 但是,當我檢查類型讀者的之後,我用它來調用函數它讓我錯誤Cannot convert type T to RFIDeas_Wrapper.
使用GetType()檢查其類型後,將通用類型轉換爲引用類型。怎麼樣?
編輯
private List<string> GetTagCollection<T>(T Reader)
{
TagCollection = new List<string>();
if (Reader.GetType() == typeof(RFIDeas_Wrapper))
{
((RFIDeas_Wrapper)Reader).OpenDevice();
// here Reader is of type RFIDeas_Wrapper
//, but i m not able to convert Reader into its datatype.
string Tag_Id = ((RFIDeas_Wrapper)Reader).TagID();
//Adds Valid Tag Ids into the collection
if(Tag_Id!="0")
TagCollection.Add(Tag_Id);
}
else if (Reader.GetType() == typeof(AlienReader))
TagCollection = ((AlienReader)Reader).TagCollection;
return TagCollection;
}
((RFIDeas_Wrapper)閱讀器).OpenDevice();
((AlienReader)Reader).TagCollection;
我想這條線沒有任何問題執行。由於讀者將永遠是我指定的類型。 如何讓編譯器理解同樣的事情。
爲什麼你使用'T'(可以是任何東西),如果您需要'RFIDeas_Wrapper'? – Bobby 2010-06-16 09:26:30
@Bobby:我可以找到任何一種閱讀器。即AlienReader在其他部分如此等等。我必須使這個函數適用於所有返回List Collection的讀者。我認爲直接傳遞類對象並獲得結果時應該是一種更好的方法,而不必一次又一次地寫相同的代碼來獲得某些輸出。 – 2010-06-16 09:27:55
我看不出在這裏使用泛型的一點,因爲你沒有得到任何編譯時類型的安全。它也可能是對象。 – 2010-06-16 09:33:59