在 C# 中是否可以用值实例化 class?
In C# is it possible to instantiate a class with a value?
在 C# 中是否可以用值实例化 class?也就是说,如果class包含一个数组,是否可以创建一个class,在实例化class时传递所需数组的长度?
是
public class MyClass
{
private readonly string[] _myArray;
public MyClass(int arrayLength)
{
_myArray = new string[arrayLength];
}
}
var myClass = new MyClass(5);
是的。
最明显的方法是使用 class:
的构造函数
class X
{
public int[] MyArray
{
get;
set;
}
public X(int arrayLength)
{
MyArray = new int[arrayLength];
}
}
您现在可以实例化它:
X myX = new X(5);
您还可以实例化一个 class 使用它的属性:
class X
{
public int[] MyArray
{
get;
set;
}
public int ArrayLength
{
set
{
MyArray = new int[value];
}
}
}
并按如下方式调用:
X myX = new X { ArrayLength = 5};
我会选择第一个选项...
您可以将长度作为构造函数参数传递。构造函数看起来像一个与 class 同名的方法,但没有 return 类型(甚至没有 void
)。
public class MyClass
{
public MyClass(int arrayLength)
{
MyArray = new string[arrayLength];
}
public string[] MyArray { get; }
}
此解决方案仅使用 getter 属性。您可以在构造函数中或使用 属性 初始化程序对其进行初始化,但是一旦创建了对象,它就是只读的。
您可以像这样创建一个 MyClass
对象:
var obj = new MyClass(10);
string firstElementOfArray = obj.MyArray[0];
string lastElementOfArray = obj.MyArray[9];
但是请选择比 MyClass
或 MyArray
更好的名称。真实姓名必须提供信息。 Class 可以命名为 Student
或 Vehicle
或 Invoice
。该数组可以命名为 Grades
、Passengers
或 InvoiceLineItems
.
但根据您的要求,该数组可以只是一个私有字段,无法从 class 外部访问。
在 C# 中是否可以用值实例化 class?也就是说,如果class包含一个数组,是否可以创建一个class,在实例化class时传递所需数组的长度?
是
public class MyClass
{
private readonly string[] _myArray;
public MyClass(int arrayLength)
{
_myArray = new string[arrayLength];
}
}
var myClass = new MyClass(5);
是的。
最明显的方法是使用 class:
的构造函数class X
{
public int[] MyArray
{
get;
set;
}
public X(int arrayLength)
{
MyArray = new int[arrayLength];
}
}
您现在可以实例化它:
X myX = new X(5);
您还可以实例化一个 class 使用它的属性:
class X
{
public int[] MyArray
{
get;
set;
}
public int ArrayLength
{
set
{
MyArray = new int[value];
}
}
}
并按如下方式调用:
X myX = new X { ArrayLength = 5};
我会选择第一个选项...
您可以将长度作为构造函数参数传递。构造函数看起来像一个与 class 同名的方法,但没有 return 类型(甚至没有 void
)。
public class MyClass
{
public MyClass(int arrayLength)
{
MyArray = new string[arrayLength];
}
public string[] MyArray { get; }
}
此解决方案仅使用 getter 属性。您可以在构造函数中或使用 属性 初始化程序对其进行初始化,但是一旦创建了对象,它就是只读的。
您可以像这样创建一个 MyClass
对象:
var obj = new MyClass(10);
string firstElementOfArray = obj.MyArray[0];
string lastElementOfArray = obj.MyArray[9];
但是请选择比 MyClass
或 MyArray
更好的名称。真实姓名必须提供信息。 Class 可以命名为 Student
或 Vehicle
或 Invoice
。该数组可以命名为 Grades
、Passengers
或 InvoiceLineItems
.
但根据您的要求,该数组可以只是一个私有字段,无法从 class 外部访问。