Con il termine "covariance" si intende la possibilità di far tornare, come tipo di ritorno in un delegate, il tipo stesso definito nella firma del delegate o di un suo tipo derivato.
1: using System;
2: using System.Collections.Generic;
3: using System.Text;
4:
5: namespace DelegateCovariance
6: {
7: class Person
8: {
9: public string Name {get;set;}
10: public int Age { get; set; }
11: public Person GetPerson()
12: {
13: Console.WriteLine("Person created");
14: return new Person();
15: }
16: }
17:
18: class Student : Person
19: {
20: public string SchoolName { get; set; }
21: public Student GetStudent()
22: {
23: Console.WriteLine("Student created");
24: return new Student();
25: }
26: }
27:
28: class GraduateStudent : Student
29: {
30: public int GraduationYear { get; set; }
31: public GraduateStudent GetGraduateStudent()
32: {
33: Console.WriteLine("GraduateStudent created");
34: return new GraduateStudent();
35: }
36: }
37:
38: class DelegateContainer
39: {
40: //Defining a delegate that returns a Person type
41: public delegate Person GetHimHandler();
42: public GetHimHandler GetHim;
43:
44: public void RaiseEvent()
45: {
46: if (GetHim != null)
47: {
48: //Invoking subscribed methods
49: GetHim();
50: }
51: }
52: }
53:
54:
55: class App
56: {
57: public static void Main(string[] args)
58: {
59: DelegateContainer delegateContainer = new DelegateContainer();
60: //Due to covariance delegates can be charged with methods that give back the return type defined on the delegate
61: //or its inhered types.
62: delegateContainer.GetHim += new DelegateContainer.GetHimHandler(new Person().GetPerson);
63: delegateContainer.GetHim += new DelegateContainer.GetHimHandler(new Student().GetStudent);
64: delegateContainer.GetHim += new DelegateContainer.GetHimHandler(new GraduateStudent().GetGraduateStudent);
65: delegateContainer.RaiseEvent();
66: Console.ReadLine();
67: }
68:
69: }
70:
71: }
No Comments
You can leave the first : )