在我的 .NET 4.0 应用程序中,我通过ISettings
我准备的接口访问应用程序属性:
public interface ISettings
{
int Quota { get; }
string Property2 { get; }
// ...
int PropertyN { get; }
}
// code generated by Visual Studio
public sealed partial class Settings :
global::System.Configuration.ApplicationSettingsBase
{
// application properties generated from app.config
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("123")]
public int Quota {
get {
return ((int)(this["Quota"]));
}
}
// and so on...
}
// my code to apply the interface to the Settings class
public sealed partial class Settings : ISettings
{
}
在某些情况下,我想根据我正在为其处理数据的组织覆盖配置文件中的值,例如,我想增加某些组织的配额。当然,我可以创建类似于:
public int GetQuotaByOrgId(int orgId);
并在那里实现逻辑,但我想避免orgId
在代码中传递。对我来说更好的解决方案是创建一个代理类,只覆盖我想要更改的值,例如:
public class OverridenSettings : ISettings
{
private ISettings instance;
private int orgId;
private int[] orgsWithBiggerQuota = {1, 2, 132, 6542};
public OverridenSettings(ISettings instance, int orgId)
{
this.instance = instance;
this.orgId = orgId;
}
public override int Quota
{
get
{
int quota = this.instance.Quota;
if (this.orgsWithBiggerQuota.Contains(this.orgId))
{
quota += 1000;
}
return quota;
}
}
// all other properties should be taken from the default instance
}
有没有一种优雅的方式来生成这样的类,而不必显式地实现所有接口的成员只是为了将它们重定向到默认实例?