Generics Object Reference Type Int 32 Value Type
Generics Object -> Reference Type Int 32 -> Value Type Reference - ל Value Type המרה בין - Boxing. Type Value - ל Reference Type – המרה בין Unboxing. Type. מוגדר בזמן כתיבה ולא בזמן ריצה T – Type Safe public class Stack { object[] m_Items; public void Push(object item) {. . . } public object Pop() {. . . } } public class Stack<T> { T[] m_Items; public void Push(T item) {. . . } public T Pop() {. . . } } Stack<int> stack = new Stack<int>(); stack. Push(1); stack. Push(2); int number = stack. Pop(); : Generics לפני : Generics עם
Generics : דוגמה נוספת : Generics § לפני : Generics § עם public struct Point<T> { public T X; public T Y; } Point<int> point; point. X = 1; point. Y = 2; Point<double> point; point. X = 1. 2; point. Y = 3. 4; public struct Point. Int { public int X; public int Y; } public struct Point. Double { public double X; public double Y; } public struct Point { public object X; public object Y; } : או לחילופין
Generics List<int> arr 1 = new List<int>(); arr 1. Add(100); arr 1. Add(200); arr 1. Add(300); arr 1. Add(400); arr 1. Add(500); : List - שימושים List<Person> arr 2 = new List<Person>(); arr 2. Add(new Person("Elimelech", "Zorkin", 65, 123456)); arr 2. Add(new Person("Zelda", "Gurnisht", 44, 4545454)); arr 2. Add(new Person("Zrubavel", "Berkovitch", 32, 8854646)); arr 2. Add(new Person("Vladimir", "Swisa", 12, 3434843)); List. Sample : דוגמת קוד Generic. List. Sample : דוגמת קוד
Generics class My. Generic. Array<T> { private T[] m_Arr; private int m_Counter; public My. Generic. Array() { m_Arr = new T[16]; } public void Add(T t) { if (m_Counter >= m_Arr. Length) Array. Resize(ref m_Arr, m_Arr. Length + 16); m_Arr[m_Counter++] = t; } public T this[int index] { get { return m_Arr[index]; } } public void Print() { for (int i = 0; i < m_Counter; i++) { Console. Write. Line(m_Arr[i]); } } } : שימושים – יצירת רשימות מותאמות static void Main(string[] args) { My. Generic. Array<int> arr 1 = new My. Generic. Array<int>(); arr 1. Add(100); arr 1. Add(200); arr 1. Add(300); arr 1. Add(400); arr 1. Add(500); arr 1. Print(); My. Generic. Array<Person> arr 2 = new My. Generic. Array<Person>(); arr 2. Add(new Person("Elimelech", "Zorkin", 65, 123456)); arr 2. Add(new Person("Zelda", "Gurnisht", 44, 4545454)); arr 2. Add(new Person("Zrubavel", "Berkovitch", 32, 8854646)); arr 2. Add(new Person("Vladimir", "Swisa", 12, 3434843)); arr 2. Print(); } Generic. Sample 01 : דוגמת קוד
Generics static void Swap<T>(ref T t 1, ref T t 2) { T tmp = t 1; t 1 = t 2; t 2 = tmp; } static void Main(string[] args) { int num 1 = 11; int num 2 = 22; Console. Write. Line("num 1={0}, num 2={1}", num 1, num 2); Swap(ref num 1, ref num 2); Console. Write. Line("num 1={0}, num 2={1}", num 1, num 2); } : שימושים – מתודות גנריות string str 1 = "Elchanan"; string str 2 = "Sonya"; Console. Write. Line("str 1={0}, str 2={1}", str 1, str 2); Swap(ref str 1, ref str 2); Console. Write. Line("str 1={0}, str 2={1}", str 1, str 2); Generic. Method : דוגמת קוד
Generics class My. Generic. List<T>: List<T> { public void Print() { for (int i = 0; i < base. Count; i++) { Console. Write. Line(base[i]); } } } הרחבת היכולות List של : List שימושים – הורשה של static void Main(string[] args) { My. Generic. List<string> arr 1 = new My. Generic. List<string>(); arr 1. Add("Shoshana"); arr 1. Add("Yerachmiel"); arr 1. Add("Zelda"); arr 1. Add("Pirchiya"); arr 1. Add("Zalman"); arr 1. Add("Fruma"); arr 1. Print(); } Generic. Method : דוגמת קוד
Generics interface IMy. Interface<T> { void Print(); } class Person : IMy. Interface<Person> { … } class My. Generic. Array<T> { private T[] m_Arr; private int m_Counter; … } static void Main(string[] args) { My. Generic. Array<Person> arr 1 = new My. Generic. Array<Person>(); arr 1. Add(new Person("Elimelech", "Zorkin", 65)); arr 1. Add(new Person("Zelda", "Gurnisht", 44)); arr 1. Add(new Person("Muhamad", "Berkovitch", 32)); arr 1. Add(new Person("Vladimir", "Swisa", 12)); arr 1. Print. All(); } : שימושים – ממשקים
Generics public delegate void Change. Delegate<T>(T t); class Person { private string m_First. Name; private string m_Last. Name; private int m_Age; public event Change. Delegate<string> First. Name. Change. Notify; public event Change. Delegate<string> Last. Name. Change. Notify; public event Change. Delegate<int> Age. Change. Notify; . . . public string First. Name { get { return m_First. Name; } set { if (value != m_First. Name) { m_First. Name = value; First. Name. Change. Notify(m_First. Name); } } הגדרת גנרי Delegate : Delegate – § שימושים Event הגדרת Event הפעלת Generic. Delegate : דוגמת קוד
Generics static void Main(string[] args) { Change. Delegate<Person> del = new Change. Delegate<Person>(Program. Func); Person p = new Person("Isaschar", "Shemyafe", 78); p. Last. Name. Change. Notify += Last. Name. Change. Notify; p. First. Name. Change. Notify += First. Name. Change. Notify; p. Age. Change. Notify += Age. Change. Notify; p. Last. Name = "Havakook"; p. Last. Name = "Loshemyafe"; p. Age = 100; del(p); } : המשך Delegate – § שימושים Event- רישום ל static void Age. Change. Notify(int t) { Console. Write. Line("New Age: " + t); } Generic. Delegate : דוגמת קוד
Generics static void Swap<T>(ref T t 1, ref T t 2) where T: struct אילוצים { T tmp = t 1; t 1 = t 2; t 2 = tmp; } int num 1 = 11; int num 2 = 22; static void Swap 2<T>(ref T t 1, ref T t 2) where T : IMy. Interface Swap(ref num 1, ref num 2); { Other o 1 = new Other(); T tmp = t 1; Other o 2 = new Other(); t 1 = t 2; Swap(ref o 1, ref o 2); t 2 = tmp; } class IMy. Interface { } class My. Class : IMy. Interface { } Generic. Constraints 01 : דוגמת קוד int num 1 = 11; int num 2 = 22; My. Class c 1 = new My. Class(); My. Class c 2 = new My. Class(); Swap 2(ref c 1, ref c 2); Swap 2(ref num 1, ref num 2);
Generics אילוצים class My. Generic. Array 1<T> where T: class { private T[] m_Arr; private int m_Counter; …. } class Base { class Derived class Other { struct Point { } : Base { } } } My. Generic. Array 1<Derived> arr 1 = new My. Generic. Array 1<Derived>(); My. Generic. Array 1<Point> arr 2 = new My. Generic. Array 1<Point>(); Generic. Constraints 01 : דוגמת קוד
Implicit Typing - Var § Beginning in Visual C# 3. 0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent: var i = 10; // implicitly typed int i = 10; //explicitly typed § Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the. NET Framework class library. For more information about how to initialize arrays with var, see Implicitly Typed Arrays (C# Programming Guide). § The following examples show various ways in which local variables can be declared with var: var i = 5; // s is compiled as a string var s = "Hello; " § It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type. § The var keyword may be used in the following contexts: § On local variables (variables declared at method scope) as shown in the previous example. § In a for initialization statement. foreach(var item in list {. . . }(
Anonymous Methods : delegate רישום והפעלה של , § דוגמת קוד הפשוטה הבאה מציגה הגדרה delegate void My. Delgate(); class Program { static void Main(string[] args) { My. Delgate my_delegate = new My. Delgate(Func); my_delegate(); } הפעלה public static void Func() { Console. Write. Line("Delegate Invoked"); } } רישום יכולה להיקרא Delegate - שנועדה להיקרא על ידי ה Func למעשה המתודה - § הבעיה . על ידי כל חלק אחר של התוכנית מבלי שיוצריה התכוונו לכך
Anonymous Methods : Event § ועם הגדרה delegate void My. Delegate(string msg); class Program { public static event My. Delegate My. Event; static void Main(string[] args) { My. Event += delegate(string msg) { Console. Write. Line("msg : {0}", msg); }; My. Event("Event Invoked"); } } אירוע רישום הפעלה
Lambda Expression delegate int My. Delegate(int i); Delegate הגדרת class Program { static void Main(string[] args) { השיטה הוותיקה // C# 1. 0 - The traditional way My. Delegate del 1 = new My. Delegate(Handler 1); int result = del 1(5); Console. Write. Line("C# 1. 0 version - The traditional way : " + result); // C# 2. 0 - With Anonymous Methods Anonymous My. Delegate del 2 = delegate(int x) { return x * x; }; Methods result = del 2(5); Console. Write. Line("C# 2. 0 - With Anonymous Methods : " + result); // C# 3. 0 - With Lambda Expression My. Delegate del = x => x * x; Lambda result = del(5); Console. Write. Line("C# 3. 0 - With Lambda Expression : " + result); } public static int Handler 1(int x) שימו לב שאין התייחסות לערך המוחזר , מחייב זאת Delegate - למרות שה {. החזרת הערך מתבצעת בצורה מרומזת return x * x; } : דוגמת קוד Lambda. Expression. Sample 01 : דוגמה
Lambda Expression : ביטוי למבדה שמקבל מספר פרמטרים , דוגמה public delegate int Calc. Something(int n 1, int n 2, int n 3); class Program { static void Main(string[] args) { Calc. Something sum_del = (n 1, n 2, n 3) => n 1 + n 2 + n 3; Calc. Something mul_del = (n 1, n 2, n 3) => n 1 * n 2 * n 3; Calc. Something div_del = (n 1, n 2, n 3) => n 1 / n 2 / n 3; Console. Write. Line(sum_del(11, 22, 33)); Console. Write. Line(mul_del(2, 3, 4)); Console. Write. Line(div_del(1000, 10, 2)); } } : דוגמת קוד Lambda. Expression. Sample 02 Delegate הגדרת Lambda
Lambda Expression class Program { static void Main(string[] args) { List<int> list = new List<int> { 1, 43, 6, 12, 5, 23, 7, 86, 3, 49 }; // C# 1. 0 style List<int> greater_than_10 = list. Find. All(new redicate<int>(Greater. Than. Ten)); foreach (int num in greater_than_10) { Console. Write(num + ", "); } Console. Write. Line(); Predicate Delegate - דוגמת קוד // C# 3. 0 style greater_than_10 = list. Find. All(num => num > 10); foreach (int num in greater_than_10) { Console. Write(num + ", "); } Console. Write. Line(); // C# 2. 0 style greater_than_10 = list. Find. All(delegate(int num) { return num > 10; }); foreach (int num in greater_than_10) { Console. Write(num + ", "); } Console. Write. Line(); } : דוגמת קוד } public static bool Greater. Than. Ten(int num) { return num > 10; }
3); Lambda Expression Action Delegate public delegate void Action<T>( T obj ). (Overloading) פרמטרים ואינו מחזיר ערך 1 -16 שמקבל בין Delegate class Program { שימוש ב private static int result = 0; Action static void Main(string[] args) { Action<int, int> Sum = (n 1, n 2) => result = n 1 + n 2; Sum(11, 22); Console. Write. Line(result); למבדה תוך Delegate- string message 1 = "The first line of a message. "; string message 2 = "The second line of a message. "; string message 3 = "The third line of a message. "; Action<string, string> print = (s 1, s 2, s 3) => Write. To. Console(s 1, s 2, print(message 1, message 2, message 3); } static void Write. To. Console(string 1, string 2, string 3) { Console. Write. Line("{0}n{1}n{2}", string 1, string 2, string 3); } : דוגמת קוד . מייצג פעולה בלבד , כשמו כן הוא למבדה תוך שימוש ב Action Delegate-
; Lambda Expression Action Delegate List<T>. For. Each( Action<T> action) static void Main() { List<String> names = new List<String>() { "Elimelech", "Zrubavel", "Havakuk", "Yerachmiel" // C# 1. 0 style names. For. Each(Print); // C# 2. 0 style names. For. Each(delegate(String name) { Console. Write. Line(name); }); // C# 3. 0 style names. For. Each(str=>Console. Write. Line(str)); } private static void Print(string s) { Console. Write. Line(s); } : דוגמת קוד
Lambda Expression למבדה תוך שימוש ב Func Delegate- Func Delegate public delegate TResult Func<T, TResult>( T arg ) Func<double, double> Square = x => x * x; var result 1 = Square(5); Console. Write. Line(result 1); Func<double, double> Mul = (x, y) => x * y; var result 2 = Mul(5, 3); Console. Write. Line(result 2); . פרמטרים ומחזיר ערך 1 -16 שמקבל בין Delegate. מייצג פעולה עם ערך מוחזר למבדה תוך שימוש ב Func Delegate- Func<double[], double> Sum. Array= (x, y) => { var dim = Math. Min(x. Length, y. Length); למבדה תוך שימוש ב var sum = 0. 0; Func Delegatex. To. List(). For. Each(num => sum += num); y. To. List(). For. Each(num => sum += num); return sum; }; double[] arr 1 = new double[] { 1. 1, 2. 2, 3. 3, 4. 4 }; double[] arr 2 = new double[] { 1. 1, 2. 2, 3. 3 }; var result 3 = Sum. Array(arr 1, arr 2); : דוגמת קוד
Lambda Expression Func Delegate List<T>. Average<TSource> Method (IEnumerable<TSource>, Func<TSource, Decimal>) static void Main(string[] args) { int[] arr = { 100, 200, 300, 400, 500 }; double average = arr. Average(num => num); Console. Write. Line("The average is {0}. ", average); } static void Main(string[] args) { int[] arr = { 100, 200, 300, 400, 500 }; double average = arr. Average(num => num + 100); Console. Write. Line("The average is {0}. ", average); } static void Main(string[] args) { string[] fruits = { "Elimelech", "Zrubavel", "Havakuk", "Yerachmiel" }; double average = fruits. Average(s => s. Length); Console. Write. Line("The average string length is {0}. ", average); } : דוגמת קוד
Lambda Expression List - ביטויי למבדה ב . מכילה מספר פונקציות המתבססות על ביטויי למבדה List : הבא List - בדוגמאות הבאות נתבסס על ה List<String> names = new List<String>() { "Elimelech", "Zelda", "Zrubavel", "Yona", "Zalman", "Pirhiya", "Fruma" }; "Havakuk", "Yerachmiel", : מיון var tmp 1 = names. Order. By(str => str). To. List(); tmp 1. For. Each(str => Console. Write. Line(str)); : דוגמת קוד
Lambda Expression : מיון בסדר יורד var tmp 2 = names. Order. By. Descending(str => str). To. List(); tmp 2. For. Each(str => Console. Write. Line(str)); var tmp 3 = names. Where(str => str. Length > 6). To. List(); tmp 3. For. Each(str => Console. Write. Line(str)); : דוגמת קוד : סינון
Lambda Expression : מיון ע"פ קריטריון names. Sort((str 1, str 2) => str 1. Length. Compare. To(str 2. Length)); names. For. Each(str => Console. Write. Line(str)); : קיבוץ var tmp 6 = names. Group. By(str => str. Length). To. List(); tmp 6. For. Each(arr => { Console. Write. Line(arr. Count()); arr. To. List(). For. Each(str => Console. Write. Line(str)); });
Lambda Expression : הבא List - בדוגמאות הבאות נתבסס על ה List<Dog> dogs = new new }; new Dog Dog List<Dog>() { { Name = "Shuka", Age = 14 }, { Name = "Lucy", Age = 2 }, { Name = "Atraf", Age = 13 }, { Name = "Sig", Age = 8 }, : בחירת שדה var names 1 = dogs. Select(x => x. Name). To. List(); names 1. For. Each(str => Console. Write. Line(str)); dogs. Where(dog=>dog. Age%2==0). Order. By(x => x. Name). To. List(). For. Each(dog => Console. Write. Line(dog. Name)); : דוגמת קוד : 1 שרשור ביטויים
Lambda Expression dogs. Where(dog => dog. Age > 5). Order. By(dog => dog. Age). To. List(). For. Each(dog => Console. Write. Line(dog. Name)); : דוגמת קוד : 2 שרשור ביטויים
Lambda Expression : למבדה ואירועים public Main. Window() { Initialize. Component(); btn. Click += (sender, e) => lbl. Content = txt. Text; } Lambda. Expression. With. WPF : דוגמת קוד
Lambda Expression // Sample 01 Func<int, int> Square = (int x) => x * x; var result 1 = Square(10); Console. Write. Line("Sample 01 - " + result 1); : שעשועי למבדה // Sample 02 Func<int, int> Mul = (int num 1, int num 2, int num 3) => num 1 * num 2 * num 3; var result 2 = Mul(2, 3, 4); Console. Write. Line("Sample 02 - " + result 2); // Sample 03 Func<int[], int> Biggest = (int[] arr) => { int biggest = int. Min. Value; arr. To. List(). For. Each(num => biggest = (num > biggest) ? num : biggest); return biggest; }; int[] arr 1 = new int[] { 1, 43, 66, 2, 88, 34, 51, 78, 99, -1, 77, 62 }; var result 3 = Biggest(arr 1); Console. Write. Line("Sample 03 - " + result 3);
Lambda Expression //Sample 04 Func<string, int> Square. String. Length = (string s) => s. Length * s. Length; var result 4 = Square. String. Length("Abra Kadabra"); Console. Write. Line("Sample 04 - " + result 4); // Sample 05 Predicate<string> Error. Str = (string s) => { if (s. Length == 0) return true; else return false; }; Func<string, string> Who. Is. Longer = (string str 1, string str 2) => { if (Error. Str(str 1) || Error. Str(str 2)) return "Error"; if (str 1. Length == str 2. Length) return "String are same length"; if (str 1. Length > str 2. Length) return str 1; else return str 2; }; var result 5 = Who. Is. Longer("Nissim Veniflaot", "Abra Kadabra"); Console. Write. Line("Sample 05 - " + result 5); : שעשועי למבדה
- Slides: 42