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# 语法通过数组中的构造函数参数初始化自定义类/对象?
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01