1

我在这里读到了这个问题:

有没有办法覆盖 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#),那会对此有影响吗?

4

2 回答 2

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)
于 2010-04-15T22:41:14.890 回答
0

使用 VB 时,不应将实现标记为,Partial而应简单地标记为Private. 看下面的例子:

Private Sub OnCreated()
    ' Your code here'
End Sub
于 2010-04-15T20:02:24.757 回答