使用静态类不会带来大问题,但是单例模式可能更适合这种情况。
public class RegistrationConfig {
// private static instance
private static RegistrationConfig _instance = new RegistrationConfig()
// private constructor prevents the class from being instantiated from outside
private RegistrationConfig() { }
// instance public accessor
public static RegistrationConfig Current { get { return _instance; } }
public int InvitationToken { get; set; }
public int InvitationDollar { get;set; }
}
消费:
var credit = new Credit();
credit.Token = RegistrationConfig.Current.InvitationToken;
一种变体不是实现单例模式,而是保留 .Current 访问器并定义一个公共设置器,以便您可以更改活动配置。
public class RegistrationConfig {
// current
private static RegistrationConfig _current;
// instance public accessor
public static RegistrationConfig Current { get { return _current; } }
// public setter
public static void SetCurrent(RegistrationConfig current)
{
_current = current;
}
public int InvitationToken { get; set; }
public int InvitationDollar { get;set; }
}
然后,在应用程序启动时设置配置。
RegistrationConfig.SetCurrent(new RegistrationConfig() { ... });
并消费:
credit.Token = RegistrationConfig.Current.InvitationToken;
优点是您可以创建具有预定义值的实例以使用,例如,在单元测试中。