本主题包括下列各节。
![]() |
---|
|
private Program() { //An aggregate catalog that combines multiple catalogs var catalog = new AggregateCatalog(); //Adds all the parts found in the same assembly as the Program class catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly)); //Create the CompositionContainer with the parts in the catalog _container = new CompositionContainer(catalog); //Fill the imports of this object try { this._container.ComposeParts(this); } catch (CompositionException compositionException) { Console.WriteLine(compositionException.ToString()); } }
static void Main(string[] args) { Program p = new Program(); //Composition is performed in the constructor String s; Console.WriteLine("Enter Command:"); while (true) { s = Console.ReadLine(); Console.WriteLine(p.calculator.Calculate(s)); } }
public interface IOperation { int Operate(int left, int right); } public interface IOperationData { Char Symbol { get; } }
[Export(typeof(IOperation))] [ExportMetadata("Symbol", '+')] class Add: IOperation { public int Operate(int left, int right) { return left + right; } }
public String Calculate(String input) { int left; int right; Char operation; int fn = FindFirstNonDigit(input); //finds the operator if (fn < 0) return "Could not parse command."; try { //separate out the operands left = int.Parse(input.Substring(0, fn)); right = int.Parse(input.Substring(fn + 1)); } catch { return "Could not parse command."; } operation = input[fn]; foreach (Lazy<IOperation, IOperationData> i in operations) { if (i.Metadata.Symbol.Equals(operation)) return i.Value.Operate(left, right).ToString(); } return "Operation Not Found!"; }
private int FindFirstNonDigit(String s) { for (int i = 0; i < s.Length; i++) { if (!(Char.IsDigit(s[i]))) return i; } return -1; }
catalog.Catalogs.Add(new DirectoryCatalog("C:\\SimpleCalculator\\SimpleCalculator\\Extensions"));
[Export(typeof(SimpleCalculator.IOperation))] [ExportMetadata("Symbol", '%')] public class Mod : SimpleCalculator.IOperation { public int Operate(int left, int right) { return left % right; } }
联系客服