如何在声明成员变量时无需重复指定类型?(C#与VB.NET对比)
Great question! Let's break down how to avoid repeating type declarations when initializing member variables in VB.NET, since you already know how this works in C# and older VB versions.
The key here is leveraging Option Infer (introduced in VB.NET 10 / Visual Studio 2010) and understanding syntax differences between modern and legacy VB versions.
1. Modern VB.NET (VS2010+) with Option Infer On
This is the closest equivalent to C#'s var for member variables—you don't need to specify the type at all, and the compiler will infer it directly from the initialization value.
- First, ensure
Option Infer Onis enabled (it's turned on by default in new projects, but double-check old projects or add it at the top of your file if needed). - Use the syntax
Dim [VariableName] = New [Type](...)for member variables—noAskeyword required.
Example Code:
Option Infer On Option Strict On ' Recommended for type safety Public Class ContentManager ' Compiler infers type: Dictionary(Of String, System.Text.StringBuilder) Dim Content = New Dictionary(Of String, System.Text.StringBuilder)() Sub ProcessContent() ' Local variables work the same way Dim tempContent = New Dictionary(Of String, System.Text.StringBuilder)() End Sub End Class
Pro tip: Pairing Option Infer On with Option Strict On gives you type safety without the boilerplate of repeating types.
2. Legacy VB.NET (Pre-VB 10, no Option Infer)
In versions before Option Infer existed, you can still avoid repeating the type using the As New shorthand. This syntax tells the compiler to use the type from the New expression as the variable's type.
Example Code:
Public Class ContentManager ' Shorthand that avoids repeating the type Dim Content As New Dictionary(Of String, System.Text.StringBuilder)() End Class
This is equivalent to writing Dim Content As Dictionary(Of String, System.Text.StringBuilder) = New Dictionary(Of String, System.Text.StringBuilder)()—but without the redundant type declaration.
Quick Comparison to C#
For context, C# has more restrictions here:
- Local variables use
var, but member variables can't usevar(even in modern C#). - C# 10+ introduced target-typed new expressions for members, letting you write:
public class ContentManager { private Dictionary<string, System.Text.StringBuilder> Content = new(); }
VB.NET's Option Infer gives you even more flexibility for member variables than modern C# does!
内容的提问来源于stack exchange,提问作者FastAl

