Trying to understand an example of a wikipedia strategy template using the new Func <int, int, int>

I looked at this, http://en.wikipedia.org/wiki/Strategy_pattern , and I understand the concept of a strategy template, but can anyone explain the C # a bit example.

I really do not understand how and why the definition of "Strategy" in the Context class, why is it Func<T, T, T> , but then only two parameters are passed, for example, 8.9?

 static void Main(string[] args) { var context = new Context<int>(); // Delegate var concreteStrategy1 = new Func<int, int, int>(PerformLogicalBitwiseOr); // Anonymous Delegate var concreteStrategy2 = new Func<int, int, int>( delegate(int op1, int op2) { return op1 & op2; }); // Lambda Expressions var concreteStrategy3 = new Func<int, int, int>((op1, op2) => op1 >> op2); var concreteStrategy4 = new Func<int, int, int>((op1, op2) => op1 << op2); context.Strategy = concreteStrategy1; var result1 = context.Execute(8, 9); context.Strategy = concreteStrategy2; var result2 = context.Execute(8, 9); context.Strategy = concreteStrategy3; var result3 = context.Execute(8, 1); context.Strategy = concreteStrategy4; var result4 = context.Execute(8, 1); } static int PerformLogicalBitwiseOr(int op1, int op2) { return op1 | op2; } class Context<T> { public Func<T, T, T> Strategy { get; set; } public T Execute(T operand1, T operand2) { return this.Strategy != null ? this.Strategy(operand1, operand2) : default(T); } } 
+7
c # design-patterns strategy-pattern
source share
4 answers

A Func<T1,T2,TResult> is a delegate of the form:

 TResult function(T1 arg1, T2 arg2) 

therefore Func has 2 types of arguments and 1 return type. Therefore, when using the func function, you type

  (arg1, arg2) => return new TResult(); 
+9
source share

Func<int, int, int> is a func that takes two int arguments and returns int - the last type in the Func definition is the return type.

+3
source share

A Func<T, T1, T2> is a delegate. A delegate is a type that represents a single function. In C #, you can use such functions instead of declaring a specific interface. If you want, you can use an interface that will look something like this:

 interface IStrategy { T Compute<T1, T2>(); } 
+1
source share

A Func<T, T1, T2> is a delegate, and any delegate can be considered as an anonymous interface .

0
source share

All Articles