이 문서는 학습 및 지식 공유를 목적으로 번역되었습니다. 저작권은 원저자에게 있으며, 상업적 용도로 사용할 수 없습니다.
지역 변수 타입 추론
VB 9.0에서는 As 절 없이 변수 선언이 가능하며, 컴파일러가 초기화 식을 통해 변수의 타입을 자동으로 결정합니다. 이는 C#의 var 키워드와 유사한 동작을 제공하지만, 강력한 형식 안정성을 유지합니다:
Dim x = 2.3 ' Double
Dim y = x ' Double
Dim r = x / y ' Double
Dim s = "sample" ' String
Dim l = s.Length ' Integer
Dim w = d ' Decimal
단, Option Strict On 설정 시 초기화되지 않은 변수 선언은 허용되지 않습니다. 이 설정은 박싱 연산을 방지하고 타입 안전성을 높여줍니다.
확장 메서드
VB 9.0에서 확장 메서드는 <Extension()> 속성을 사용하여 정의됩니다. 메서드와 이를 포함하는 모듈 모두에 해당 속성이 필요합니다:
Imports System.Runtime.CompilerServices
<Extension()>
Public Module ExtensionMethods
<Extension()>
Public Function ToEuro(amount As Decimal) As String
Return FormatCurrency(amount, 2, TriState.True, TriState.False, TriState.True)
End Function
<Extension()>
Public Function ToUSD(amount As Decimal) As String
Return FormatCurrency(amount, 2, TriState.False, TriState.False, TriState.True)
End Function
End Module
사용 시에는 해당 모듈을 Imports 문으로 포함시켜야 합니다:
Imports FinancialExtensions.ExtensionMethods
Sub Main()
Dim price As Decimal = 1234.56
Console.WriteLine(price.ToEuro())
Console.WriteLine(price.ToUSD())
End Sub
객체 초기화 구문
VB 9.0의 객체 초기화 구문은 중괄호 내에 속성 할당 목록을 포함하여 단일 표현식으로 객체 생성과 초기화를 동시에 수행할 수 있습니다:
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Property City As String
End Class
' 기본 생성자 사용
Dim person1 = New Person With {
.Name = "홍길동",
.Age = 30,
.City = "서울"
}
' 매개변수 있는 생성자와 혼합 사용
Dim person2 = New Person("김철수", 25) With {
.City = "부산"
}
익명 형식
클래스 이름을 명시하지 않고 New 키워드를 사용하면 익명 형식이 생성됩니다:
Dim employee1 = New With {.Name = "박영희", .Department = "개발팀"}
Dim employee2 = New With {.Name = "이민수", .Salary = 4500000}
' 속성 순서와 타입이 동일해야 같은 익명 형식으로 간주
Dim employee3 = New With {.Name = "최지영", .Department = "디자인팀"}
Dim employee4 = New With {.Department = "마케팅", .Name = "정우성"} ' 다른 형식
쿼리 식
VB 9.0의 LINQ 쿼리는 SQL과 유사한 구문을 제공합니다. 기본 구조는 From-Where-Select 패턴을 따릅니다:
Dim employees = {
New With {.Name = "김개발", .Salary = 4000000, .Dept = "IT"},
New With {.Name = "박디자인", .Salary = 3500000, .Dept = "Design"},
New With {.Name = "이영업", .Salary = 3000000, .Dept = "Sales"}
}
Dim highEarners = From emp In employees
Where emp.Salary > 3200000
Select New With {.EmployeeName = emp.Name, .Annual = emp.Salary * 12}
OrderBy 절 사용 시 C#과 위치가 다릅니다:
' VB 9.0
Dim sortedQuery = From emp In employees
Select result = New With {.Name = emp.Name, .Pay = emp.Salary}
Order By result.Pay Descending
' C# 대응
var sortedQuery = from emp in employees
orderby emp.Salary descending
select new {emp.Name, Pay = emp.Salary};
Lambda 표현식
VB 9.0의 Lambda 표현식은 Function 키워드를 사용합니다:
' 단일 매개변수
Function(x) x * 2
' 다중 매개변수
Function(a, b) a + b
' 조건식
Function(customer) customer.City = "서울"
' 리스트 필터링 예제
Dim customers As New List(Of Customer)
Dim seoulCustomers = customers.FindAll(Function(c) c.City = "서울")
클로저
Lambda 표현식 내에서 외부 범위의 변수를 참조할 때 클로저가 생성됩니다:
Dim minAge = 25
Dim maxAge = 40
Dim filtered = From person In people
Where person.Age >= minAge AndAlso person.Age <= maxAge
Select person.Name
컴파일러는 위 코드를 다음과 같이 변환합니다:
Dim minAge = 25
Dim maxAge = 40
Dim filtered = Enumerable.Select(
Enumerable.Where(people,
Function(p) p.Age >= minAge AndAlso p.Age <= maxAge),
Function(p) p.Name)