vb.net对象初始化列表(Of T)

前端之家收集整理的这篇文章主要介绍了vb.net对象初始化列表(Of T)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在看一些C#代码
List<Employee> Employees = new List<Employee>{
    new Employee{firstname="Aamir",lastname="Hasan",age=20},new Employee{firstname="awais",age=50},new Employee{firstname="Bill",age=70},new Employee{firstname="sobia",lastname="khan",age=80},};

现在我把它转换成vb.net

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

我得到错误“在对象初始化程序中初始化的字段或属性名称必须以’.’开头.

现在我可以使用代码获取一组员工:

Dim Employees = { 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 _
} _  
}

但是我想要一个List(Employee)列表,因为它是在告诉我为什么这不工作在vb.net?

编辑(2)
正如评论中指出的那样,现在已经介绍了 VB.NET collection initializers,并且很多以下的帖子应该被视为过时的.

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

结果是VB.NET doesn’t have collection initializers.这意味着没有等同性

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

…但它确实有对象初始化器.因此,您可以创建一个类的实例,并一次性向其属性分配值,但是您不能一次创建列表的实例并向其中添加项.

你最近可以得到的是在上面的链接.您可以创建一个Array并在单个操作中添加项,然后必须ToList该数组.

所以这一次我自己编写了代码,并且它的工作原理.对不起,麻烦

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

    Dim Employees as List(Of Employee) = EmployeesTemp.ToList()
原文链接:https://www.f2er.com/vb/255739.html

猜你在找的VB相关文章