1

2 つの派生クラス (Sale と ServiceCharge) があります。どちらもトランザクションです。BusinessService がある場合は、その ServiceCharge を作成したいと考えています。Product を渡す場合は、Sale をインスタンス化します。

これが私の考えです。

private void CreateInstance(object element)
{
    Transaction transaction;
    if (element.GetType() == typeof(BussinessService))
    {
        transaction = new ServiceCharge((BussinessService)element))
    }
    else
    {
        transaction = new Sale((Product)element);
    }
{

もっとエレガントな方法を教えてください。単一のコンストラクターのみでジェネリックを使用する方法を知っています

private void CreateInstance<T>(T element)
{
   Transaction transaction = new Transaction((T)element);
}

しかし、最初のケースでうまくいく方法がわかりません。

4

4 に答える 4

6

次のようなジェネリック インターフェイスを定義します。

public interface ITransactionable<T>
    where T : Transaction
{
    T CreateTransaction();
}

BussinessServiceそしてあなたのとを次のように飾りますProduct

public class BussinessService :
    ITransactionable<ServiceCharge>
{
    public T CreateTransaction() 
    { 
        return new ServiceCharge(this);
    }
}

public class Product :
    ITransactionable<Sale>
{
    public T CreateTransaction() 
    { 
        return new Sale(this);
    }
}

これで、ジェネリック メソッドを次のように定義できます。

private void CreateInstance<T>(ITransactionable<T> element)
{
   Transaction transaction = element.CreateTransaction();
   ...
}
于 2013-07-16T15:54:48.777 に答える
6

この場合、単純なインターフェースでも機能します。

interface ITransactionable
{
    Transaction CreateTransaction();
}

class BusinessService : ITransactionable
{
    public Transaction CreateTransaction() { return new ServiceCharge( this ); }
}

class Product : ITransactionable
{
    public Transaction CreateTransaction() { return new Sale( this ); }
}

private void CreateInstance(ITransactionable element)
{
   Transaction transaction = element.CreateTransaction();
   ...
}   
于 2013-07-16T16:00:28.460 に答える
1

BusinessServiceProductおそらくインターフェイスを共有することによって、何らかの方法でポリモーフィックである必要があります。

interface IChargable<out T> where T : Transaction
{
    Transaction Charge();
}

このように実装されたインターフェースは、

class BusinessService : IChargable<ServiceCharge>
{
    public ServiceCharge Charge()
    {
        return new ServiceCharge(...
    }
}

class Product : IChargable<Sale>
{
    public Sale Charge()
    {
        return new Sale(...
    }
}

これは、このようなコードが機能することを意味します

var chargables = new IChargable<Transaction>[]
    {
        new BusinessService(),
        new Product()
    };

var transactions = chargables.Select(c => c.Charge());    
于 2013-07-16T16:44:47.020 に答える