如何使用static / singleton设计模式实现这一点?

时间:2014-01-29 10:28:13

标签: c# static singleton

我想实现一个配置助手。

用法将是这样的:

var companyName = ConfigHelper.Company.Name;
var redirectURL = ConfigHelper.URLs.DefaultRedirectURL; 

正如您在上面的示例中所看到的,我有ConfigHelper,它不需要实例,但它将包含子类(公司和URL),在这里我想要访问属性(而不是方法)。

我希望这一切都完成,不需要任何类实例,并且不确定我是否应该使用static / singleton。

我不需要确切的代码 - 但我想样本会很好,而只是寻找正确方向的一个点。

提前致谢。

2 个答案:

答案 0 :(得分:2)

public static class Company
{
    public const string Name = "Company Name";
}

public static class ConfigHelper
{
    public static readonly Company = new Company();
}

答案 1 :(得分:1)

是的,你是在正确的轨道上,ConfigHelper将是一个静态类,属性将只是常规类,但那些 将是实例。

例如:

public class Company
{

    public string Name { get; set; }

}

public static class ConfigHelper
{

    static ConfigHelper()
    {
        Company = new Company();
    }

    public static Company Company { get; private set; }

}