我有一組類,每個類都可以使用外部應用程序打開不同類型的文件,並告訴應用程序將文件打印到特定的打印機。這些類都繼承了一個通用的抽象類和一個接口。類的字典
internal interface IApplicationPrinter : IDisposable
{
string ApplicationExe { get; }
string ApplicationName { get; }
string[] PrintableExtensions { get; }
IApplicationPrinter CreateInstance(string Filename, string Printer);
void Print();
bool ExitApplicationAfterPrint { get; set; }
bool WaitApplicationExitOnPrint { get; set; }
System.IO.FileInfo PdfFile { get; protected set; }
}
internal abstract class ApplicationPrinter : IApplicationPrinter
{
...
}
internal class WordPrinter : ApplicationPrinter
{
internal static string[] PrintableExtensions { get { return new string[]{".doc", ".docx" }; } }
...
}
internal class ExcelPrinter : ApplicationPrinter
{
internal static string[] PrintableExtensions { get { return new string[]{".xls", ".xlsx" }; } }
...
}
我試圖創建可打印的文件擴展名的Dictionary
和相應的可打印這些文件類Type
秒。我做不是想要實例化字典中的類。
private static Dictionary<string, Type> FileConverters;
static Printer()
{
FileConverters = new Dictionary<string, Type>();
foreach (string ext in WordPrinter.PrintableExtensions)
{
FileConverters.Add(ext, typeof(WordPrinter));
}
string filename = "textfile.txt";
string extension = filename.Substring(filename.LastIndexOf("."));
if (FileConverters.ContainsKey(extension))
{
IApplicationPrinter printer = ((IApplicationPrinter)FileConverters[extension]).CreateInstance(filename, "Printer");
printer.Print();
}
}
有沒有什麼辦法讓Dictionary<string, Type> FileConverters
更加類型安全,通過把它限制爲實現IApplicationPrinter值?換句話說,是這樣的可能:
private static Dictionary<string, T> FileConverters where T: IApplicationPrinter;
更新: 我不想存儲實例有以下兩個原因:
- 每個類都可以處理多個不同的文件類型(見
string[] PrintableExtensions
)。該字典將擴展名存儲爲密鑰。創建和存儲同一個類的多個分離實例沒有實用性。 - 每個打印機類都使用COM API和Office Interop來創建第三方應用程序的實例。如果需要,最好爲打印作業創建每個類的新實例,並且垃圾收集器可以在之後進行清理。
爲什麼你不想在字典中存儲實例? – svick 2012-01-28 11:13:27