我有一组类,每个类都可以使用外部应用程序打开不同类型的文件,并告诉该应用程序将文件打印到特定打印机。这些类都继承了一个通用的抽象类和一个接口(interface)。
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 创建第三方应用程序的实例。最好在需要时为打印作业创建每个类的新实例,然后垃圾收集器可以清理。
最佳答案
我会略有不同:
private Dictionary<String, Func<IApplicationPrinter>> _converters;
public void Initialise()
{
foreach (string ext in WordPrinter.PrintableExtensions)
{
_converters.Add(ext, () => new WordPrinter());
}
}
public IApplicationPrinter GetPrinterFor(String extension)
{
if (_converters.ContainsKey(extension)) //case sensitive!
{
return _converters[extension].Invoke();
}
throw new PrinterNotFoundException(extension);
}
此方法不会按照您的要求将实例存储在字典中,而是会在您每次调用GetPrinterFor
时为您创建一个新实例。 .作为 Func<>
的返回类型,它的类型也更强。必须是 IApplicationPrinter
.
关于c# - 类类型字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9044734/