Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Even though James' method is ideal, using an IoC container could be difficult. Here's my Reflection or dynamics based approach. Doing the following will allow you to still use an IoC to setup the mapping between the <code>PaymentTaker</code> and <code>Payment</code>.</p> <pre><code>public class Payment { } public class CreditCardPayment : Payment { } public class StoreCreditPayment : Payment { } public interface IPaymentTaker { } public interface IPaymentTaker&lt;T&gt; : IPaymentTaker { void Process(T payment); } public static class PaymentTaker { public static void Process(Payment payment) { var paymentType = payment.GetType(); // You would have these already setup and loaded via your IOC container... var paymentTakers = new Dictionary&lt;Type, IPaymentTaker&gt;(); paymentTakers.Add(typeof(CreditCardPayment), new CreditCardPaymentTaker()); paymentTakers.Add(typeof(StoreCreditPayment), new StoreCreditPaymentTaker()); // Get the payment taker for the specific payment type. var paymentTaker = paymentTakers[paymentType]; // Execute the 'Process' method. paymentTaker.GetType().GetMethod("Process").Invoke(paymentTaker, new object[]{ payment }); // If .NET 4.0 - dynamics can be used. // dynamic paymentTaker = paymentTakers[paymentType]; // paymentTaker.Process((dynamic)payment); } } public class CreditCardPaymentTaker : IPaymentTaker&lt;CreditCardPayment&gt; { public void Process(CreditCardPayment payment) { Console.WriteLine("Process Credit Card Payment..."); } } public class StoreCreditPaymentTaker : IPaymentTaker&lt;StoreCreditPayment&gt; { public void Process(StoreCreditPayment payment) { Console.WriteLine("Process Credit Card Payment..."); } } </code></pre> <p>And then you can use it like this:</p> <pre><code>var cc = new CreditCardPayment(); PaymentTaker.Process(cc); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload