c#静态类声明

时间:2012-05-26 00:04:11

标签: c# class static instantiation

下面代码的目的是返回一个包含相关数据集的静态类。你能推荐一下我能做得更好吗?

public class People
{
    //want info to be setup in this class, so it can be accessed elsewhere
    public static readonly string[] ab = { "ALBERT", "EINSTEIN"};       
    public static readonly string[] dk = { "DONALD", "KNUTH" };

   //is this efficient or instantiated once per access? IF SO HOW CAN I DO THIS BETTER? 
    public static readonly Info AB = new Info(ab, 100); 
    public static readonly Info DK = new Info(dk, 80);

}

public class Info
{
    private string[] _name;
    private int _age;

    public string[] Name { get{ return _name}; }
    public int Age { get { return _age; } }

    public Info(string[] n, int a)
    {
        _name = n;
        _age = a;
    }
}

1 个答案:

答案 0 :(得分:3)

  

每次访问是高效还是实例化一次?

如果您指的是构建Info实例的时刻,则会在第一次访问该成员之前构建它们。所以无论你拨打People.AB多少次,对象都是一样的。

从MSDN了解Static Classes and Static Class Members

  

静态成员在第一次访问静态成员之前和静态构造函数(如果有的话)被调用之前被初始化。

如果你想使Info的实例完全不可变(正如Daniel所说,一旦你获得对数组的引用就可以改变_name的值),你可以改变类型_name及其属性访问者:

private List<string> _name;

public IList<string> Name { get { return _name.AsReadOnly(); } }

希望我了解您的需求!