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

明確にするために

これはあなたの条件ですか?

  • UserAccountService と UserAccount はライブラリ A にあります
  • ExtendedUserAccount はあり、ライブラリ B にのみ存在します
  • ライブラリ A を編集できない/編集したくない場合

答えは次のようになります。これを可能にするライブラリ B のエントリ ポイントを 1 つ作成します。

于 2013-11-05T14:31:13.627 に答える