15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Mef architecture ❘ 753<br />

operations. This calculator can be used in place of the other one by copying the assembly to the directory<br />

that is specified by the DirectoryCatalog in the hosting application.<br />

using System;<br />

using System.Collections.Generic;<br />

using System.ComponentModel.Composition;<br />

namespace Wrox.ProCSharp.MEF<br />

{<br />

[Export(typeof(ICalculator))]<br />

public class Calculator : ICalculator<br />

{<br />

public IList GetOperations()<br />

{<br />

return new List()<br />

{<br />

new Operation { Name="+", NumberOper<strong>and</strong>s=2},<br />

new Operation { Name="-", NumberOper<strong>and</strong>s=2},<br />

new Operation { Name="/", NumberOper<strong>and</strong>s=2},<br />

new Operation { Name="*", NumberOper<strong>and</strong>s=2},<br />

new Operation { Name="%", NumberOper<strong>and</strong>s=2},<br />

new Operation { Name="++", NumberOper<strong>and</strong>s=1},<br />

new Operation { Name="--", NumberOper<strong>and</strong>s=1}<br />

};<br />

}<br />

}<br />

}<br />

public double Operate(IOperation operation, double[] oper<strong>and</strong>s)<br />

{<br />

double result = 0;<br />

switch (operation.Name)<br />

{<br />

case "+":<br />

result = oper<strong>and</strong>s[0] + oper<strong>and</strong>s[1];<br />

break;<br />

case "-":<br />

result = oper<strong>and</strong>s[0] - oper<strong>and</strong>s[1];<br />

break;<br />

case "/":<br />

result = oper<strong>and</strong>s[0] / oper<strong>and</strong>s[1];<br />

break;<br />

case "*":<br />

result = oper<strong>and</strong>s[0] * oper<strong>and</strong>s[1];<br />

break;<br />

case "%":<br />

result = oper<strong>and</strong>s[0] % oper<strong>and</strong>s[1];<br />

break;<br />

case "++":<br />

result = ++oper<strong>and</strong>s[0];<br />

break;<br />

case "--":<br />

result = --oper<strong>and</strong>s[0];<br />

break;<br />

default:<br />

throw new InvalidOperationException(<br />

String.Format("invalid operation {0}", operation.Name));<br />

}<br />

return result;<br />

}<br />

code snippet AdvCalculator/Calculator.cs<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!