C# Class 与子项

C# Class with Sub-Items

比方说,我想要一个包含许多子class的主class,子class都具有相同的properties/methods,我需要在许多不同的其他代码部分访问它们。

示例: 主要class:国家

子 classes / 项目:德国、荷兰、大不列颠、法国、...

然后为每个国家/地区定义单独的属性,例如人口、单位……

所以稍后在代码中我可以像

一样访问它
if (Country.France.Units < Country.Germany.Units)
Console.WriteLine("foo");

编辑:感谢大家的回答,CodeCaster 的解决方案非常适合我的目的。其他人也是对的,通过字符串值解析字典只是更少的工作...

您不希望这样做,因为对于添加的每个国家/地区,您都必须重新编译,这意味着您无法自动 link 将数据从外部数据源加载到静态类型的属性.

改用字典:

var countries = new Dictionary<string, Country>();

// ...

if (countries["France"].Units < ...)

如果你不喜欢字典的字符串解析,而且你的列表比较小,你可以这样做:

List<Country> counties = new List<Country>();
countries.Add(France as Country);
countries.Add(Germany as Country);
...

var France = countries.FirstOrDefault(t => t is France);

特别是为了解决当前任务,您可以创建一个 class 国家,每个国家都有私有构造函数和静态属性。

public class Country
{
    private Country()
    {
    }

    public int Population {get; private set;}

    // Static members

    public static Country USA {get; private set;}
    public static Country Italy {get; private set;}

    static Country()
    {
        USA = new Country { Population = 100000 };
        Italy = new Country { Population = 50000 };
    }
}

您可以通过以下代码访问

Country.USA.Population < Country.Italy.Population

您想要的听起来与 Color 结构非常相似。它有大量预定义的 classes 但仍然允许 "custom" 颜色。

然而,与 Color 不同的是,Country 具有可能随时间变化的属性,并且可能受益于可以更新的外部数据源。国家的数量也是有限的,因此您可以通过不让成千上万的 "France" 实例四处浮动来优化内存。

一种适合的模式是 Flyweight。您可以使用工厂方法最大限度地减少浮动对象的数量,但仍然可以轻松访问一组预定义的国家/地区:

public class Country
{
    // properties of a Country:
    public int Population {get; private set;}
    public string Units {get; private set;}
    // etc.

    // Factory method/fields follows

    // storage of created countries
    private static Dictionary<string, Country> _Countries = new Dictionary<string,Country>();

    public static Country GetCountry(string name)
    {
        Country country;
        if(_Countries.TryGetValue(name, out country))
            return country;
        //else
        country = new Country();
        // load data from external source
        _Countries[name] = country;
        return country;
    }

    public static Country France { get {return GetCountry("France");} }
    public static Country Germany { get {return GetCountry("Germany");} }
}

按原样设计的一些注意事项:

  • 它不是线程安全的。您需要添加适当的线程安全。
  • 国家不是永恒的——如果一个预先定义的国家不复存在,你会怎么做?
  • 理想情况下,工厂将是一个单独的 class,因此您可以将 Country class 与工厂分离,但我认为 Country.France 看起来比CountryFactory.France