C# 语法通过数组中的构造函数参数初始化自定义类/对象?

C# syntax to initialize custom class/objects through constructor params in array?(C# 语法通过数组中的构造函数参数初始化自定义类/对象?)

本文介绍了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# 语法通过数组中的构造函数参数初始化自定义类/对象?

基础教程推荐