在一行代码中初始化对象属性

reg*_*gex 8 c# vb.net

题:

大家好,

对不起,这是一个菜鸟问题.我只是不知道如何说出这个过程,所以我不确定谷歌会采取什么措施.我将在下面放一些C#代码来解释我正在尝试做什么.我只是不知道如何在VB中做到这一点.另外,对于将来的参考,如果你能告诉我这个过程被称为什么,那么知道它会很有帮助.在此先感谢您的帮助.

// Here is a simple class
public class FullName
{
    public string First { get; set; }
    public char MiddleInintial { get; set; }
    public string Last { get; set; }

    public FullName() { }
}

/* code snipped */

// in code below i set a variable equal to a new FullName 
// and set the values in the same line of code
FullName fn = new FullName() { First = "John", MiddleInitial = 'J', Last = "Doe" };
Console.Write(fn.First);  // prints "John" to console
Run Code Online (Sandbox Code Playgroud)

正如我之前提到的那样,如果这个问题重复,我会在搜索什么内容上留下空白.我也讨厌重播:)所以,如果你找到了什么,请把我链接到其他地方.


解:

所以感谢我们其中一位成员的帮助,我发现关键字是With.

Dim fn As New FullName() With { .First = "John", .MiddleInitial = "J"c, .Last = "Doe" }
Console.Write(fn.First)  ' prints "John" to console
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 15

这是一个对象初始化器.

公平的VB.NET代码将是:

Dim fn = New FullName() With {.First = "John", .MiddleInitial = 'J', .Last = "Doe" }
Run Code Online (Sandbox Code Playgroud)

VB.NET引用MSDN上.