Pat*_*ick 3 .net c# ms-office office-interop
我有一个函数,它接受一个word文档并以html格式保存.我想使用相同的函数来处理任何文档类型.由于Jon Skeet指出,我尝试使用泛型(我假设不同的doc API是相同的)失败了.还有另外一种方法吗?
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 );
Run Code Online (Sandbox Code Playgroud)
不,这是不可能的.类型参数用于类型,而不是名称空间.
特别是,编译器无法验证是否存在这样的类型 - 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
}
Run Code Online (Sandbox Code Playgroud)
然后:
ConvertDocToHtm2<Word.Application>(filename);
Run Code Online (Sandbox Code Playgroud)
(我已经猜到了参数名称trueValue- 你想要验证它.)