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

查看:93
本文介绍了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引擎2的网页.但是我认为这是一个普通的C#问题?

I dunno 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.

想知道我在上面的代码中缺少什么...?

Wondering what I am missing in the above code...?

推荐答案

尝试在新的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#语法通过数组中的构造函数参数初始化自定义类/对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆