English 中文(简体)
c# 静态级声明
原标题:c# static class declaration
Hi the intent of the code below is to return a static class which holds a related set of data. Can you recommend how I can do this better? 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; } }
最佳回答
is this efficient or instantiated once per access? If you mean the moment at when the instances of Info are constructed, they are built before the first access to the member. So no matters how many times you call People.AB, the object will be the same. From MSDN about Static Classes and Static Class Members: Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called. If you want to make your instances of Info totally immutable (as Daniel says, the values of _name could be changed once you get a reference to the array), you can change the type of _name and its property accesor to: private List _name; public IList Name { get { return _name.AsReadOnly(); } } Hope I ve understood your needs!
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签