如何静态声明对象数组
我是一名资深 C 程序员,但对 C# 还很陌生。我想声明一个对象,然后创建一个该对象的数组,静态填充它(我有一个非常大的表要输入)。例如,
class MyObject {
int i1;
string s1;
double d1;
};
static MyObject[] myO = new MyObject {{1,"1",1.0}, {2,"2",2.0}};
这不起作用,但你明白了。任何帮助表示赞赏。
I'm a long time C programmer but new to C#. I want to declare an object then creating an array of that object filling it statically (I have a very large table to enter). For example
class MyObject {
int i1;
string s1;
double d1;
};
static MyObject[] myO = new MyObject {{1,"1",1.0}, {2,"2",2.0}};
This doesn't work but you get the idea. Any help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
假设您的班级有公共字段/属性:
Assuming you have public fields/properties on your class:
您需要用对象实例填充数组。
创建一个带有参数的构造函数,然后编写
You need to fill the array with object instances.
Create a constructor that takes parameters, then write
您必须使用新的对象实例初始化数组。
不幸的是,无法像内置类型或字典的数组一样指定自定义初始值设定项。为了(未来)参考我的意思:
You'll have to initialize the array with new object instances.
Unfortunately there is no way to specify custom initializers like they are for arrays of built-in types or dictionaries. For (future) reference of what I mean:
您需要实例化数组中的对象:
You'll need to instantiate the objects in the array:
这正是您想要的,但您可以通过以下代码实现您的目标:
It is exactly what you want but you can achieve your goal with following code:
我在这里看到一些问题。首先,您的所有变量都是私有的。其次,您没有调用构造函数。
I see a few things wrong here. Firstly all your variables are private. Secondly you are not calling a constructor.
尝试
Try