我有一个使用许可的库,我想创建一个基于输入返回正确许可的函数。
这是我使用的类的简化版本:
public class Settings {
private Aspose.Words.License lic;
private Aspose.Pdf.License plic; // new license
public License License {
get {
if (this.lic == null) {
this.lic = new License();
this.lic.SetLicense("Aspose.Total.lic");
}
return this.lic;
}
}
}所以您可以看到,有两个许可文件存在,一个在Aspose.Words名称空间中,一个在Aspose.Pdf名称空间中。
有更多的许可,但在本例中,我使用的是2
那么,您将如何修改它返回正确许可的license属性。
我的第一个go将是函数中的开关情况,并以字符串的形式插入,但我不知道您是否可以根据名称空间值请求?
发布于 2015-07-23 08:02:50
我在Aspose.PDF v9.6.0中签了名,Aspose.Pdf.License似乎是一个独立的类,没有基类,没有接口。
如果同样的代表你的情况,那就没有办法了。由于Aspose.Words.License和Aspose.Pdf.License是完全不相关的,所以没有办法有条件地将它们从相同的属性中返回,除非
第一种解决方案有一个缺点--无论何时您想使用它,都需要将对象转换回正确的许可类型。在使用中非常令人恼火。
第二种解决方案有一个缺点--您的代码会变得复杂,您可能需要将许多其他代码从Settings更改为Settings<X>。
public class Settings<TLic> where TLic : class, new(){
private TLic wlic;
public TLic License {
get {
if (this.lic == null) {
dynamic temp = new TLic();
temp.SetLicense("Aspose.Total.lic");
this.lic = temp;
}
return this.lic;
}
}
}用法:
var sett1 = new Settings<Aspose.Words.License>();
var wordsLicense1 = sett1.License;
var sett2 = new Settings<Aspose.Pdf.License>();
var pdfLicense2 = sett2.License;编辑:
OOorr..您可以像Fabjan建议的那样将该属性重写为一种方法。这将使您免于更新所有“设置”引用,但将强制您更新所有proeprty引用并进行方法调用。
事后考虑:如果您正在处理许多项目中使用的一段通用代码,如果您的每个项目只使用一种许可证类型的,那么通过使用一些肮脏的继承技巧,您实际上可以在不更新refences的情况下获得成功:)
public class SettingsBase<TLic> where TLic : class, new(){
private TLic wlic;
public TLic License {
get {
if (this.lic == null) {
dynamic temp = new TLic();
temp.SetLicense("Aspose.Total.lic");
this.lic = temp;
}
return this.lic;
}
}
}项目中的使用-1:
// in another file
public class Settings : SettingsBase<Aspose.Words.License> { }
// then
var sett = new Settings();
var wordsLicense = sett.License;在项目2中的使用:
// in another file
public class Settings : SettingsBase<Aspose.Pdf.License> { }
// then
var sett = new Settings();
var pdfLicense = sett.License;发布于 2015-07-23 08:00:33
首先,我会使用指令使事情变得更简单:
using WordsLicense = Aspose.Words.License;
using PdfLicence = Aspose.Pdf.License;然后,我们可以创建一个返回实例的泛型方法(使用泛型属性会更方便,但不幸的是,它们目前仍在开发中):
public class Settings {
private WordsLicense wlic;
private PdfLicence plic;
public static T GetLicense<T>() where T : class
{
if (typeof(T) == typeof(WordsLicense)) { if (wlic == null) wlic = new WordsLicense(); return wlic as T; }
if (typeof(T) == typeof(PdfLicence)) { if (plic == null) plic = new PdfLicence(); return plic as T; }
return null;
}
}https://stackoverflow.com/questions/31581021
复制相似问题