c#静态类声明

c#静态类声明,c#,class,static,instantiation,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 = {

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

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;
    }
}
这是有效的还是每次访问实例化一次

如果您指的是构建
Info
实例的时刻,则它们是在首次访问成员之前构建的。因此,无论您调用
People.AB
多少次,对象都是相同的

来自MSDN关于:

在第一次访问静态成员之前以及在调用静态构造函数(如果有)之前初始化静态成员

如果要使
Info
的实例完全不可变(正如Daniel所说,一旦获得对数组的引用,
\u name
的值就可以更改),可以将
\u name
的类型及其属性accesor更改为:

private List<string> _name;

public IList<string> Name { get { return _name.AsReadOnly(); } }
private List\u name;
公共IList名称{get{return _Name.AsReadOnly();}

希望我了解你的需要

仅供参考,值
Name
是可变的。为什么选择在getter中使用IList?由于私有变量_name已经在使用具体的列表类型,这是因为
AsReadOnly()
方法返回一个
ReadOnlyCollection
实例,该实例实现
IList
接口,但不扩展
List
类,因此无法转换。