开发者

Initialize Dictionary in .Net 2.0

开发者 https://www.devze.com 2022-12-12 21:42 出处:网络
Is there a simple way to initialize a dictionary that is a property like in .Net 3.5 or do I need to add the elements in the class\'s constructor开发者_运维问答?

Is there a simple way to initialize a dictionary that is a property like in .Net 3.5 or do I need to add the elements in the class's constructor开发者_运维问答?

My aim is to have a static map of codes mapping to string representation.


Yes, you'll need to initialize your Dictionary at class constructor.


The Collection Initializer syntax is only available for Dictionaries in .NET 3.5 and going forward.

FTA:

This feature (collection initialization) requires the C# 3.0 compiler wich was introduced with Visual Studio 2008 and only works with .NET 3.5 or later. Static initialization only works for arrays in previous versions.

However, you're not limited to adding the elements in your classes constructor. You can add then any time you want, you just can't do it using collection initialization.


If your class is static you can do it in a static constructor.

static myclass()
{
    //Do stuff here?!
}

If it's not, do it in your instance constructor?

0

精彩评论

暂无评论...
验证码 换一张
取 消