2017-07-05 148 views
0

我試圖將下面的C#代碼轉換爲VB.NET。問題在於lambda表達式。將C#Lambda轉換爲VB.NET

public class UserStore 
{ 
    private readonly IDatabaseFactory _databaseFactory; 

    private DataContext _db; 
    protected DataContext Db => _db ?? (_db = _databaseFactory.GetDataContext()); 

    public UserStore(IDatabaseFactory databaseFactory) 
    { 
     _databaseFactory = databaseFactory; 
    } 
} 

以下是我所轉換的代碼:

Public Class UserStore 
    Private ReadOnly _databaseFactory As IDatabaseFactory 

    Private _db As DataContext 
    Protected Db As DataContext = Function() As DataContext 
            If _db Is Nothing Then 
             _db = _databaseFactory.GetDataContext() 
            End If 
            Return _db 
            End Function 

    Public Sub New(databaseFactory As IDatabaseFactory) 
     _databaseFactory = databaseFactory 
    End Sub 
End Class 

出於某種原因,轉換後的拉姆達給出了錯誤Lambda expression cannot be converted to 'DataContext' because 'DataContext' is not a delegate type.

誰能告訴我我在做什麼這裏錯了嗎?

+2

這不是拉姆達的只是一小段路。它是表達酒體的財產。 – PetSerAl

回答

8

我想將下面的C#代碼轉換爲VB.NET。問題在於lambda表達式。

問題是你誤認爲lambda的表達式屬性。

在C#

protected DataContext Db => _db ?? (_db = _databaseFactory.GetDataContext()); 

是寫

protected DataContext Db { 
    get 
    { 
    return _db ?? (_db = _databaseFactory.GetDataContext()); 
    } 
} 

的一小段路這不是一個拉姆達在所有;如果你想將其轉換爲VB,只需編寫一個正常的VB屬性獲取器。

注意,C#允許你做這一招與方法,以及:

public Abc Foo(Bar bar) => Blah(bar); 

是寫

public Abc Foo(Bar bar) 
{ 
    return Blah(bar); 
} 
+0

我沒有意識到這一點。謝謝! –