vb.net Object Initialiser List(Of T)

前端 未结 3 1634
时光说笑
时光说笑 2021-01-04 03:18

I have been looking at some C# code:

List Employees = new List{
    new Employee{firstname=\"Aamir\",lastname=\"Hasan\",age=2         


        
3条回答
  •  一个人的身影
    2021-01-04 03:29

    EDIT (2)
    As pointed out in comments, VB.NET collection initializers have now been introduced, and a lot of the following post should be considered obsolete.

    EDIT
    Don't always blindly trust the C# to VB.NET converter
    Here's a handy tool for online conversion

    Turns out VB.NET doesn't have collection initializers. Which means there is no equivalence of

    var myList = new List()
    {
       "abc",
       "def"
    };
    

    ... but it does have object initializers. So you can create an instance of a class and assign values to its properties all in one go, but you cannot create an instance of a list and add items to it all in one go.

    There closest you can get is in the link above. You can create an Array and add items to it in a single operation, and then you have to ToList that array.

    So this time I've actually compiled the code myself, and it works. Sorry for the hassle

        Dim EmployeesTemp As Employee() = { _
            New Employee() With { _
                .firstname = "Aamir", _
                .lastname = "Hasan", _
                .age = 20 _
            }, _
            New Employee() With { _
                .firstname = "awais", _
                .lastname = "Hasan", _
                .age = 50 _
            }, _
            New Employee() With { _
                .firstname = "Bill", _
                .lastname = "Hasan", _
                .age = 70 _
            }, _
            New Employee() With { _
                .firstname = "sobia", _
                .lastname = "khan", _
                .age = 80 _
            } _
        }
    
        Dim Employees as List(Of Employee) = EmployeesTemp.ToList()
    

提交回复
热议问题