开发者

how do I dynamically create and name objects at runtime in C#?

I wish to dynamically create and name instances of my object at runtime as I add them to a list class I somehow thought this would be a simple matter in c# but thus far I have been unable to find any information on how to achieve this.

for the brief description I have a custom class that during runtime I wish to create an array list and populate it with objects of the custon class but name the objects as they're being added to the list using the 开发者_开发技巧loop index and a standard name.

Is this possible?


You can either have a list that allows you to access its elements by an index or have a dictonary that allows you the same with any particular type:

List<YourClass> yourList = new List<YourClass>();
YourClass instance = new YourClass();
yourList.Add(instance);
YourClass instance2 = yourList[0];

For example, if you want your dictionary with a string key ("name"):

Dictonary<string, YourClass> dict = new Dictonary<string, YourClass>();
YourClass instance = new YourClass();
dict.Add("someName", instance);
YourClass instance2 = dict["someName"];

Unlike in PHP, there's no inbuilt collection type in C# that allows you to access its members by both an index or a key. You can always create your own though.


Objects don't have names in .NET.

Also, don't use the ArrayList class. Use List<T> instead.


Sort of an odd question, as you can't "name" objects.

However you could do what it sounds like you are trying to achieve using a generic dictionary (Dictionary<string, MyCustomType>). The string key in the dictionary is sort of like an object name, and the value the key corresponds to contains the object instance.


Are you maybe looking for something like System.Collections.Generic.Dictionary<>..?


If you want to give them a name then add them to a mapping instead of a list.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜