C# 如何创建自动实例化的元素数组,例如用户定义类型的int数组?
在声明int数组时,例如:C# 如何创建自动实例化的元素数组,例如用户定义类型的int数组?,c#,.net,arrays,C#,.net,Arrays,在声明int数组时,例如: int[] test = new int[5]; 数组的所有元素都自动初始化为0。我是否可以创建一个在创建数组(如int数组)时自动初始化的类 例如: MyClass[] test2 = new MyClass[5]; 仍然需要我调用构造函数;但是使用int可以神奇地调用构造函数 int类的哪些代码/运算符允许此行为 更新: 我删除了new()的约束,以接受没有无参数构造函数的类。但是,这也会接受一个抽象类或接口用作类型参数,如果无法实例化该类型,它将在运行时引发
int[] test = new int[5];
数组的所有元素都自动初始化为0
。我是否可以创建一个在创建数组(如int数组)时自动初始化的类
例如:
MyClass[] test2 = new MyClass[5];
仍然需要我调用构造函数;但是使用int
可以神奇地调用构造函数
int
类的哪些代码/运算符允许此行为 更新:
我删除了new()
的约束,以接受没有无参数构造函数的类。但是,这也会接受一个抽象类或接口用作类型参数,如果无法实例化该类型,它将在运行时引发异常
需要进一步提及的一点是,CreateArray
方法也将处理值类型;也就是说,除了指针类型和具有TypeAttributes.Abstract
1属性的类型之外,您可以使用它创建任何类型的数组
1:接口也是抽象的。静态类是抽象和密封的
区别在于
int
是一种值类型,但您的类可能不是
将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 */ );
}
}
公共静态类TestClass{
公共静态T[]CreateArray(整型长度,参数对象[]args){
var elementType=typeof(T);
var array=(T[])array.CreateInstance(elementType,length);
对于(;长度-->0;
数组[length]=(T)Activator.CreateInstance(elementType,args))
;
返回数组;
}
公共静态void TestMethod(){
var-array=CreateArray(5,/*默认参数*/);
}
}
默认参数是传递给构造函数的参数。代码创建一个数组,然后使用给定的参数创建该类型的实例,并使用实例初始化该数组
请注意,length
作为数组大小传递,然后用作for循环中的索引
文件:
将MyClass更改为struct数据类型,即:公共结构MyClass
这里的问题是MyClass是引用类型,因此默认值为空。由于不初始化数组中的对象,因此它们为空。您可以编写以下帮助程序:
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;
}
T[]初始化array(int-length),其中T:new()
{
T[]数组=新的T[长度];
对于(int i=0;i
然后初始化阵列:
MyClass[] something = InitializeArray<MyClass>(5);
MyClass[]something=InitializeArray(5);
int
数组没有神奇地设置为0Int
是一种默认值为0的值类型,其中asMyClass
是一种默认值为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");
}
如果要创建包含所有初始化内容的数组,可以使用fluent扩展方法:
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();
public static T[]InitializeAll(此T[]源代码),其中T:new()
{
如果(源!=null)
{
对于(变量i=0;i
或mandaleeka解决方案,使用循环
编辑:我正在恢复我原来的解决方案,因为Guffa的评论需要它作为背景
public static T[] CreateArray<T>(int size) where T : new()
{
return Enumerable.Repeat(new T(), size).ToArray();
}
publicstatict[]CreateArray(int-size),其中T:new()
{
返回可枚举的.Repeat(新的T(),size.ToArray();
}
这与两者之间的差异有关
“如果数据类型在其自己的内存分配中保存数据,则它是值类型。”而“引用类型包含指向保存数据的另一个内存位置的指针。”
值类型的常见示例:
- 所有数字数据类型
- 布尔值、字符和日期
- 所有结构,即使其成员是引用类型
- 枚举,因为它们的基础类型始终是SByte、Short、Integer、Long、Byte、Short、UInteger或ULong
//un-initialized, therefore cannot be used until a value is given(A compiler error will occur)
string str;
- 串
- 所有数组,即使其元素是值类型
- 类类型,例如
- 代表
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");
}
声明:
int num;
int[] numbers = new int[5];
不初始化变量num
。因此不能使用num
。C#要求在使用每个变量之前,将其设置为某个值(无论是null
还是数字)
引用类型也是如此:
//un-initialized, therefore cannot be used until a value is given(A compiler error will occur)
string str;
但是,声明:
int num;
int[] numbers = new int[5];
使数组初始化(因此调用数组的构造函数),然后使每个元素初始化为默认值int(即零)
对引用类型使用相同的方法会产生相同的结果:
string[] strings = new string[5];
使数组初始化,从而创建一个null
字符串数组(这是所有引用类型的默认值)
是您要查找的数据类型。结构是值类型,因此不能设置为null
。由于不能将它们设置为null
,因此它们必须具有一些默认值。默认值由一个参数确定
结构可以这样定义:
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");
}
//MyStructName的数组,调用默认构造函数并初始化每个值
迈斯特