开发者

How to create an array of custom type in C#?

I created an object array with different types of elements in them:

public static int a;
public static string b;
publi开发者_开发百科c static ushort c;

object[] myobj = new obj[]{ a, b, c};

If I want to create an array that contains elements of arrays of this myobj type, how would I do it?

I mean something like this:

myobj[] myarray = new myobj[];  <= but to do this, myobj should be a type. 

Not sure how to work it out.

Thanks everyone.


Create a type containing the types you want and make an array of those.

public class MyType // can be a struct. Depends on usage.
{
  // should really use properties, I know, 
  // and these should probably not be static
  public static int a;
  public static string b;
  public static ushort c;
}

// elsewhere
MyType[] myobj = new MyType[]{};

Not sure why you would want to jump through hoops with object[] and having to cast all over the place.


How about we use a Dictionary to store any types you need?

So, while you will not exactly have myType.a, you can have myType.Values["a"], which is close enough, makes use of standard C# constructs, and gives you 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();

        for (var current = 0; current < myTypes.Length; ++current)
        {
            // here you customize what goes where
            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 you want, you can easily add an indexer property to your class, so you can access elements with the syntax myType["a"]. Notice that you should add error checking when adding or retrieving values.

public object this[object index]
{
    get
    {
        return this.Values[index];
    }

    set
    {                    
        this.Values[index] = value;
    }
}

And here's a sample using indexer. Increment the entries by '1' so we see a difference in the 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"]));
}


I made a couple of changes, but I think this would be in the spirit of what you want to do.

Since the properties are the only differentiating characteristics for array elements, 'static' makes no sense, so I removed it.

If you define the class as follows:

    public class MyType
    {
        /// <summary>
        /// Need a constructor since we're using properties
        /// </summary>
        public MyType()
        {
            this.A = new int();
            this.B = string.Empty;
            this.C = new ushort();
        }

        public int A
        {
            get;
            set;
        }

        public string B
        {
            get;
            set;
        }

        public ushort C
        {
            get;
            set;
        }
    }

You could use it like so:

using System;

public static class Program
{
    [STAThread]
    private static void Main()
    {
        var myType = new MyType[3];

        myType[0] = new MyType();
        myType[1] = new MyType();
        myType[2] = new MyType();

        for (var i = 0; i < myType.Length; ++i)
        {
            myType[i].A = 0;
            myType[i].B = "1";
            myType[i].C = 2;
        }

        // alternatively, use foreach
        foreach (var item in myType)
        {
            item.A = 0;
            item.B = "1";
            item.C = 2;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜