如何创建一个自动实例化的元素数组,例如用户定义类型的int数组?

时间:2013-06-26 01:02:57

标签: c# .net arrays

声明一个int数组,例如:

int[] test = new int[5];

数组的所有元素都自动初始化为0。无论如何我可以创建一个在创建数组时自动初始化的类,比如int数组吗?

例如:

MyClass[] test2 = new MyClass[5];

仍然需要我调用构造函数;但是使用int,构造函数被神奇地调用。

允许此行为的int类的代码/运算符是什么?

5 个答案:

答案 0 :(得分:4)

这里的问题是MyClass是一个引用类型,因此默认值为null。因为您没有初始化数组中的对象,所以它们为null。你可以写一个帮手,如:

T[] InitializeArray<T>(int length) where T : new()
{
    T[] array = new T[length];
    for (int i = 0; i < length; ++i)
    {
        array[i] = new T();
    }

    return array;
}

然后初始化你的数组:

MyClass[] something = InitializeArray<MyClass>(5);

答案 1 :(得分:4)

int数组不会神奇地设置为0. Int是一个默认值为0的值类型,其中MyClass是一个默认值为{的引用类型{1}}。

如果要创建包含所有内容初始化的数组,可以使用流畅的扩展方法:

null

或mandaleeka解决方案,使用循环。

编辑:我正在恢复我的原始解决方案,因为Guffa的评论需要它用于上下文

public static T[] InitializeAll<T>(this T[] source) where T : new()
{
    if(source != null)
    {
        for(var i = 0; i < source.Length; ++i)
        {
            source[i] = new T();
        }
    }

    return source;
}

var test2 = new MyClass[5].InitializeAll();

答案 2 :(得分:3)

<强>更新

我删除了new()的约束以接受没有无参数构造函数的类。但是,这也会接受抽象类或接口作为类型参数,如果无法实例化类型,它将在运行时抛出异常。

还有一点需要提及的是,CreateArray<T>方法还会处理值类型;也就是说,除了指针类型和具有TypeAttributes.Abstract 1 属性的类型之外,您可以使用它创建任何类型的数组。

1 :接口也是抽象的。静态类是抽象的&amp;密封。


区别在于int是值类型,但您的class可能不是。

MyClass声明为struct MyClass{ },然后它的行为与创建int数组的行为相同。

如果您确实想要创建一个引用类型数组,那么下面的代码就是这样做的:

public static class TestClass {
    public static T[] CreateArray<T>(int length, params object[] args) {
        var elementType=typeof(T);
        var array=(T[])Array.CreateInstance(elementType, length);

        for(; length-->0;
            array[length]=(T)Activator.CreateInstance(elementType, args))
            ;

        return array;
    }

    public static void TestMethod() {
        var array=CreateArray<MyClass>(5, /* default arguments */ );
    }
}

默认参数是您传递给构造函数的参数。代码创建一个数组,然后使用给定的参数创建该类型的实例,并使用实例初始化该数组。

请注意,length作为数组大小传递,然后在for循环中用作索引。

文档:

答案 3 :(得分:2)

将MyClass更改为struct数据类型,即:public struct MyClass

答案 4 :(得分:0)

这与Value Types and Reference Types之间的区别有关。

“数据类型是一种值类型,如果它将数据保存在自己的内存分配中。”而“,引用类型包含指向另一个存储数据的内存位置的指针。”

值类型的常见示例:

  • 所有数字数据类型
  • 布尔值,字符和日期
  • 所有结构,即使其成员是引用类型
  • 枚举,因为它们的基础类型始终为SByte,Short,Integer,Long,Byte,Short,UInteger或ULong

参考类型的常见示例:

  • 字符串
  • 所有数组,即使它们的元素是值类型
  • 类类型,例如Form
  • 代表

所有值类型都初始化为默认值(数字类型为零),引用类型指向null

声明:

int num;

不初始化变量num。因此无法使用num。 C#要求在使用之前将每个变量设置为某个值(null或数字)。

参考类型也是如此:

//un-initialized, therefore cannot be used until a value is given(A compiler error will occur)
string str;

然而,声明:

int[] numbers = new int[5];

使数组初始化(因此调用数组的构造函数),然后将每个元素初始化为默认值int(即零)。

在引用类型上使用相同的方法会产生相同的结果:

string[] strings = new string[5];

使数组初始化,从而创建一个null字符串数组(这是所有引用类型的默认值)。

Structures是您要查找的数据类型。结构是值类型,因此不能设置为null。由于它们无法设置为null,因此它们必须具有一些默认值。默认值由default constructor确定。

结构可以这样定义:

struct MyStructName
{
    //Members of the struct, like a class, default value is 0.
    int myNumber;

    //Structs can have members whose data type is a reference type
    //Default value is null.
    string myString;

    //Every struct has a default constructor, though you cannot define one.
    //The compiler generates one for you that initializes every member to it's
    //default value.

}

这将定义一个包含成员myNumber和myString的数据类型,这些成员不能设置为null

//Array of MyStructName, the default constructor is called and each value is initialized
MyStructName[] data = new MyStructName[5];

//Loop and print results
for(int i = 0; i < data.Length; i++)
{
    //Prints the index, number and the string or "null"
    Console.WriteLine("{0}: myNumber: {1}, myString: \"{2}\"", i, data[i].myNumber, data[i].myString != null ? data[i].myString : "null"); 
}