如何创建自定义类型在C#中的数组? [英] 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;
public static ushort c;
object[] myobj = new obj[]{ a, b, c};
如果我想创建包含此MyObj中类型的数组元素的数组,我会怎么做呢?
If I want to create an array that contains elements of arrays of this myobj type, how would I do it?
我的意思是这样的:
myobj[] myarray = new myobj[]; <= but to do this, myobj should be a type.
不知道如何解决它。
Not sure how to work it out.
谢谢大家。
推荐答案
怎么样,我们使用的 词典
存储任何类型的需要?
How about we use a Dictionary
to store any types you need?
所以,虽然你不会到底有 myType.a
,你可以有 myType.Values [一]
,这是足够接近,使得使用标准C#构造,并给你很多的灵活性/可维护性
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;
}
}
和示例用法:
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"]));
}
}
另外,如果你愿意,你可以轻松地添加一个 索引
属性类,这样你就可以用语法访问元素的myType [一]
。请注意,您应该添加错误检查添加或检索值时。
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;
}
}
而这里的使用索引的样本。按1增加的条目,所以我们看到在ouptut一个区别:
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"]));
}
这篇关于如何创建自定义类型在C#中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!