2010-04-15 74 views
1

我在這裏讀了這個問題:LINQtoSQL自定義構造函數關閉部分類?

Is there a way to override the empty constructor in a class generated by LINQtoSQL?

通常我的構造看起來像:

public User(String username, String password, String email, DateTime birthday, Char gender) 
    { 
     this.Id = Guid.NewGuid(); 
     this.DateCreated = this.DateModified = DateTime.Now; 
     this.Username = username; 
     this.Password = password; 
     this.Email = email; 
     this.Birthday = birthday; 
     this.Gender = gender; 
    } 

然而,在這個問題看,你想使用部分方法OnCreated()來替代分配值並且不覆蓋默認的構造函數。好了,所以我得到這個:

partial void OnCreated() 
{  
     this.Id = Guid.NewGuid(); 
     this.DateCreated = this.DateModified = DateTime.Now; 
     this.Username = username; 
     this.Password = password; 
     this.Email = email; 
     this.Birthday = birthday; 
     this.Gender = gender; 
} 

然而,這給了我兩個錯誤:

Partial Methods must be declared private. 
Partial Methods must have empty method bodies. 

好吧,我將其更改爲Private Sub OnCreated()刪除這兩個錯誤。然而,我仍然堅持...我如何傳遞它的價值,因爲我會與一個正常的自定義構造函數? 此外,我在VB中做這個(轉換它,因爲我知道大部分知道/喜歡C#),那麼這會對此產生影響嗎?

回答

1

您不能將值傳遞到OnCreated。您鏈接的問題涉及重寫默認構造函數的行爲。這聽起來像你想用一個參數化的構造是這樣的:

Public Sub New(username as String, password as String, email as String, birthday as DateTime, gender as Char) 
    User.New() 

    Me.Id = Guid.NewGuid() 
    Me.DateCreated = this.DateModified = DateTime.Now 
    Me.Username = username 
    Me.Password = password 
    Me.Email = email 
    Me.Birthday = birthday 
    Me.Gender = gender 
End Sub 

是否要創建新用戶是這樣的:

Dim u as User = new User() 

或像這樣:

Dim u as User = new User("Name", "Password", "Email", etc) 
+0

啊好吧我沒有想到User.New(),我試圖做我自己的構造函數,但後來當我試圖保存該對象失敗,因爲它沒有包含很多自動生成的類的東西需要默認的構造函數提供。謝謝! – SventoryMang 2010-04-16 03:01:14

+1

我只是想添加'User.New()'不起作用,您會收到以下錯誤:構造函數調用僅作爲實例構造函數中的第一條語句有效。相反,似乎工作的是'Me.New()' – SventoryMang 2010-04-25 23:06:57

+0

對不起 - 我不是很瞭解VB。希望你相當快地到達Me.New()。 – 2010-04-26 18:32:24

0

使用VB時,不應將實現標記爲Partial,而應僅將其標記爲Private。看下面的示例:

Private Sub OnCreated() 
    ' Your code here' 
End Sub 
+0

呀,我在帖子中評論說,這並不能解決我正在嘗試完成的任務,並且像在典型的自定義構造函數中那樣將一些值傳遞給OnCreated。 – SventoryMang 2010-04-15 20:07:55