0

更多信息:

编辑:更好的样本:

我在一个名为 UserAccount 的库中有一个类,它是抽象的。然后我在库中有一些这样的功能:

class UserAccountService
{
    public static UserAccount CreateUserAccount(String username, String password, String email)
    {
    UserAccount account = new UserAccount();
    account.Username = username;
    account.HashedPass = //Some crypting stuff with password
    account.Email = email;

    UserAccountRepository db = new UserAccountRepository();
    db.UserAccounts.Add(account);

    return account;
    }
}

因为这是一个独立的库,UserAccount 没有我想使用的所有属性:

class ExtendedUserAccount : UserAccount
{
// define some additional methods and propertys
public Contact Contacts{get;set}// this property is only used in one application where i use the Library....
}

然后我想这样做:

ExtendedUserAccount newAccount = UserAccountService.CreateUserAccount(new UserAccount);

但这行不通。我现在不正确,但我需要类似的东西......

有人有想法吗?

4

3 回答 3

3

这看起来像代码味道,你可能需要重新设计你的类型......但无论如何,这应该工作:

class UserAccountService
{
    public static TAccount CreateUserAccount<TAccount>(TAccount account)
          where TAccount : UserAccount, new()
    {
        //create new useraccount...
        return account;
    }
}

这个泛型方法接受一个必须扩展 UserAccount(或者是 UserAccount 本身)的类型的实例,并声明一个无参数的构造函数。最后一个限制将允许您这样做:TAccount account = new TAccount().

于 2013-11-05T13:52:23.700 回答
0

我推荐工厂模式

class UserAccountService
{
    // ctor with interfaces
    public IUserAccount CreateUserAccount()
    {
        // create instance
        return result;
    } 

    // ctor with generic
    public IUserAccount CreateUserAccount<T>() where T : UserAccount
    {
        var account = Activator.CreateInstance<T>();
        return account;
    } 
}

class ExtendedUserAccount : UserAccount
{
    // define some additional methods and propertys
}

class UserAccount : IUserAccount
{

}

internal interface IUserAccount
{
}
于 2013-11-05T13:53:37.333 回答
0

Just to make it clear

Are this you conditions?

  • UserAccountService & UserAccount are in Library A
  • ExtendedUserAccount is, and only will be in Library B
  • you can't/dont't want to edit library A

then the answer can be: Make 1 entry point in Library B that make this possible

于 2013-11-05T14:31:13.627 回答