2011-03-10 164 views
1

我有一個函數,它將一個word文檔保存爲html格式。我想使用相同的功能來處理任何文檔類型。我嘗試過使用泛型(我假設不同的doc API是相同的),由於Jon Skeet指出的原因而失敗。有另一種方法嗎?將名稱空間傳遞給函數

using Word = Microsoft.Office.Interop.Word; 
using Excel = Microsoft.Office.Interop.Excel; 

//Works ok 
private void convertDocToHtm(string filename) 
{ 
... snip 

    var app = new Word.Application(); 
    var doc = new Word.Document(); 
    doc = app.Documents.Open(ref fileName, ref missing, ref trueValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); 

... snip  
} 

//fails dismally (to compile) because 'T' is a 'type parameter', which is not valid in the given context - i.e Word is a namespace not a class 
private void convertDocToHtm2<T>(string filename) 
{ 
... snip 

    var app = new T.Application(); 
    var doc = new T.Document(); 
    doc = app.Documents.Open(ref fileName, ref missing, ref trueValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); 

... snip 
} 

//calling examples 
convertDocToHtm(filename); 
convertDocToHtm2<Word>(filename); 
convertDocToHtm2<Excel>(filename); 

回答

3

不,這是不可能的。類型參數用於類型,而不是名稱空間

特別是,編譯器無法驗證這種類型是否存在 - 例如,您可以撥打ConvertDocToHtm2<System>

隨着動態類型在C#4,你可以做一些這樣的:

private void ConvertDocToHtm2<TApplication>(string filename) 
    where TApplication : new() 
{ 
    dynamic app = new TApplication(); 
    dynamic doc = app.Documents.Open(filename, html: trueValue); 
    // Other stuff here 
} 

然後:

ConvertDocToHtm2<Word.Application>(filename); 

(我在參數名稱的方式猜對trueValue - 你想驗證一下。)

+0

嗯,看起來有趣,但我們仍然沒有移動到.net 4 ... – Patrick 2011-03-10 10:29:52

+1

@Patrick:在這種情況下,我認爲你會被卡住手動反射,或每個應用程序單獨的方法。 – 2011-03-10 10:31:46

+1

無論如何,它是沒有用的,因爲'Excel.Application'不包含名爲'Documents'的屬性,所以這個方法只能用於Word文檔。 – 2011-03-10 10:34:57

1

一旦你有對象dynamic在這裏可能很適合(用於調用方法和訪問屬性等) - 但是,那只有適用於變量,而不是名稱空間。

如果你真的需要命名空間(我不認爲你這樣做),你可以將它作爲字符串傳遞並使用Activator.CreateInstance(namespace + ".Application")

但是,閱讀它 - 似乎只有應用程序是必要的;也許是:

private void convertDocToHtm2<T>(string filename) where T : class, new(); 
{ 
    dynamic app = new T(); 
    dynamic doc = app.Documents.Open(fileName); 

    // etc 
} 

,並呼籲爲convertDocToHtm2<Word.Application>(filename)

1

這是不可能的,因爲在C#泛型是編譯時的功能和類型必須在編譯時是已知的。這是不可能的,因爲不同的Office應用程序的API不共享公共基類。在C++中它可以工作,因爲C++模板被編譯成在運行時被評估的類。但即使如此,它只會適用於小部分的API,因爲它們是而不是一樣!

1

如果您不想使用動態類型,並且只在每個名稱空間中使用幾個方法,並且這些方法具有相同的簽名,則可以構造ConvertDocToHtml2以接受委託。然後將這些方法作爲這些代表傳遞給Word/Excel。

相關問題