C# syntax to initialize custom class/objects through constructor params in array?(C# 语法通过数组中的构造函数参数初始化自定义类/对象?)
问题描述
我有一个至少有 4 个变量的类,并且我为该类创建了一个构造函数,以便我可以使用它来初始化它
I have a class with minimum 4 variables and I have made a constructor for the class so that I can initialize it with
MyClass testobj = new MyClass(1234,56789,"test text", "something else", "foo");
工作正常.
然后我有一个数组,我需要在一个循环中解析,所以我想将一些静态数据放入这个数组中.
Then I have an array of these, that I need to parse in a loop, so I would like to get some static data into this array.
我的做法是:
MyClass[] testobjlist = new MyClass
{
new MyClass(1001,1234,"Text 1", "abcdefghijklm", "ding"),
new MyClass(1002,2345,"Text xx", "bla bla", "dong"),
new MyClass(1003,8653,"Text yy", "blah blah even more", "bamm!")
}
但不知何故,这给了我一个奇怪的错误,关于我需要一个额外的 } ???
but somehow this gives me a weird error about me needing an extra } ???
我不知道该不该提这个,但是我用 Razor-engine 2 做网页.不过我觉得这是一个普通的 C# 问题?
I don't know if I should mention this, but I use it for webpages using Razor-engine 2. But I think this is an ordinary C# question?
我的解决方法目前是用一个大小初始化数组,然后通过索引一个一个地添加元素,但我更喜欢上面的解决方案,因为我可能必须在测试时按顺序上下移动项目,我实际数据中的数量远远超过 3.
My workaround is currently to initialize the array with a size, then adding the elements one by one through index, but I would rather prefere the above solution as I might have to move the items up and down in order when testing and I have a lot more than 3 in the real data.
我在上面的代码中缺少什么?
What I am missing in the above code?
推荐答案
尝试在new MyClass后面加方括号,最后加分号
Try adding square brackets after new MyClass and a semi-colon at the end
MyClass[] testobjlist = new MyClass[]
{
new MyClass(1001,1234,"Text 1", "abcdefghijklm", "ding"),
new MyClass(1002,2345,"Text xx", "bla bla", "dong"),
new MyClass(1003,8653,"Text yy", "blah blah even more", "bamm!")
};
这篇关于C# 语法通过数组中的构造函数参数初始化自定义类/对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 语法通过数组中的构造函数参数初始化自定义类/对象?


- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01