0

比方说,我想要一个包含许多子类的主类,所有子类都具有相同的属性/方法,并且我需要在许多不同的其他代码部分中访问它们。

示例:主类:国家

子类/项目:德国,荷兰,大不列颠,法国,...

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

所以稍后在代码中我可以像访问它一样

if (Country.France.Units < Country.Germany.Units)
Console.WriteLine("foo");

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

4

4 回答 4

5

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

改用字典:

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

// ...

if (countries["France"].Units < ...)
于 2015-01-13T13:53:05.333 回答
3

特别是要解决当前任务,您可以为每个国家/地区创建一个具有私有构造函数和静态属性的 Country 类。

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
于 2015-01-13T14:06:48.180 回答
1

你想要的听起来与Color结构非常相似。它具有大量预定义的类,但仍允许“自定义”颜色。

Color但是,与 不同的是,Country它的属性可能会随着时间而变化,并且可能会受益于拥有可以更新的外部数据源。还有有限数量的国家,因此您可以通过没有成千上万的“法国”实例来优化内存。

一种适合的模式是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");} }
}

设计的一些注意事项:

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

如果您不喜欢字典的字符串解析,并且您的列表相对较小,您可以这样做:

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

var France = countries.FirstOrDefault(t => t is France);
于 2015-01-13T13:58:17.323 回答