C# syntax to initialize custom class/objects through constructor params in array?

会有一股神秘感。 提交于 2019-12-18 05:38:04

问题


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");

Works fine.

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.

My approach was:

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 } ???

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?

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...?


回答1:


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!")
        };



回答2:


this will also work without a need to create a constructure

new MyClass [] { new MyClass { Field1 = "aa", Field2 = 1 } } 



回答3:


Shorthand for the win:

var myClassList = new[]
{
    new MyClass(1001,1234,"Text 1", "abcdefghijklm", "ding"),
    new MyClass(1002,2345,"Text xx", "bla bla", "dong")
};



回答4:


You want:

MyClass[] testobjlist = new MyClass[] { ... }

You were missing the brackets toward the end.




回答5:


MyClass[] testobjlist = 
    {
     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!")
    };



回答6:


MyClass[] testobjlist = new MyClass[noOfObjects];
for(int i = 0; i < testobjlist.Length; i++) { testobjlist[i] = new MyClass(); }



回答7:


You can use below code for the array:

additionalusers[] __adiitonaluser =
{
    new additionalusers()
};
__adiitonaluser[0].Email = Userpersonal.Email;


来源:https://stackoverflow.com/questions/17322250/c-sharp-syntax-to-initialize-custom-class-objects-through-constructor-params-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!