How to create an array of custom type in C#? -
i created object array different types of elements in them:
public static int a; public static string b; public static ushort c; object[] myobj = new obj[]{ a, b, c};
if want create array contains elements of arrays of myobj type, how it?
i mean this:
myobj[] myarray = new myobj[]; <= this, myobj should type.
not sure how work out.
thanks everyone.
how use dictionary
store types need?
so, while not have mytype.a
, can have mytype.values["a"]
, close enough, makes use of standard c# constructs, , gives lots of flexibility/maintainability
public class mytype { public mytype() { this.values = new dictionary<object, object>(); } public dictionary<object, object> values { get; set; } }
and sample usage:
using system; using system.collections.generic; public static class program { [stathread] private static void main() { var mytypes = new mytype[3]; mytypes[0] = new mytype(); mytypes[1] = new mytype(); mytypes[2] = new mytype(); (var current = 0; current < mytypes.length; ++current) { // here customize goes mytypes[current].values.add("a", current); mytypes[current].values.add("b", "mybvalue"); mytypes[current].values.add("c", (ushort)current); } foreach (var current in mytypes) { console.writeline( string.format("a={0}, b={1}, c={2}", current.values["a"], current.values["b"], current.values["c"])); } }
plus, if want, can add indexer
property class, can access elements syntax mytype["a"]
. notice should add error checking when adding or retrieving values.
public object this[object index] { { return this.values[index]; } set { this.values[index] = value; } }
and here's sample using indexer. increment entries '1' see difference in ouptut:
for (var current = 0; current < mytypes.length; ++current) { mytypes[current]["a"] = current + 1; mytypes[current]["b"] = "mybvalue2"; mytypes[current]["c"] = (ushort)(current + 1); } foreach (var current in mytypes) { console.writeline(string.format("a={0}, b={1}, c={2}", current["a"], current["b"], current["c"])); }
Comments
Post a Comment