Beruflich Dokumente
Kultur Dokumente
Nauzad Kapadia
Interfaces
An interface defines a contract
An interface is a type Can declare variables of that type
However, you cannot directly instantiate an interface
Includes methods, properties, indexers, events Any class or struct implementing an interface must support all parts of the contract
Interfaces
Example
public interface IDisposable { void Dispose(); } public class TextBox : IDisposable { public void Dispose() { ... } } public class Car : IDisposable { public void Dispose() { ... } } void PolyDispose(IDisposable id) { id.Dispose(); } TextBox tb = new TextBox(); PolyDispose(tb);
Car c = new Car(); PolyDispose(c);
Interfaces
Casting
A class that implements an interface can be cast (converted) to any of those interfaces
public interface IDisposable { } public interface IEnumerable { } public class ListBox : IDisposable, IEnumerable { } ListBox lb = new ListBox(); IDisposable id = (IDisposable)lb; IEnumerable ie = (IEnumerable)lb;
Interfaces
Multiple Inheritance
Interfaces can inherit from multiple interfaces Classes and structs can inherit from multiple interfaces
interface ITextBox { void SetText(string s); } interface IListBox { void SetItems(string[] items); } interface IComboBox: ITextBox, IListBox { }
Functions
Methods, properties, indexers, operators Constructors, finalizers
Type definitions
Classes, structs, enums, interfaces, delegates
Both can implement multiple interfaces Both are instantiated with new operator
Class
Reference type Can inherit from any non-sealed reference class Can have a finalizer Can have user-defined parameterless constructor Value type
Struct
C++ Struct
Same as C++ class, but all members are public Can be allocated on the heap, on the stack or as a member (can be used as value or reference), just like C++ class Members are always public
C# Struct
User-defined value type
public struct Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } } Point p = new Point(2,5); p.X += 100; int px = p.X; // px = 102
protected
internal protected internal
class Person { string name; public Person(string name) { this.name = name; } public void Introduce(Person p) { if (p != this) Console.WriteLine(Hi, Im + name); } }
class Shape { int x, y; public override string ToString() { return "x=" + x + ",y=" + y; } } class Circle : Shape { int r; public override string ToString() { return base.ToString() + ",r=" + r; } }
public class MyClass { public const string version = 1.0.0; public const string s1 = abc + def; public const int i3 = 1 + 2; public const double PI_I3 = i3 * Math.PI; public const double s = Math.Sin(Math.PI); ... }
//ERROR
public class Button: Control { private string _caption; public string caption { get { return _caption; } set { _caption = value; Repaint(); } } } Button b = new Button(); b.caption = "OK"; String s = b.caption;
Properties
Access to private fields normally requires accessors and mutators Properties allow access to private fields as if they were public
public class Person { private int age; public int Age { Property get { return age; } set { age = value; Console.WriteLine(age); } } }
C#
instead of:
Other
Write-only (implement only set) Read/write (implement both get and set)
Indexers
Index an object as if it were an array
C#
public class numbers { private int[3] nums; public int this[int index] { get { return nums[index]; } set { nums[index] = value; } } } Numbers Num = new Numbers(); Num[0] = 5; int Val = Num[0];
instead of:
Numbers Num = new Numbers(); Num.Set_Nums(0,5); int Val = Num.Get_Nums(0);
Indexer
Other
Methods have argument lists Methods contain statements Methods can return a value
Only if return type is not void
int Sum(params int[] intArr) { int sum = 0; foreach (int i in intArr) sum += i; return sum; int sum = Sum(13,87,34); }
abstract class Shape { public abstract void Draw(); } class Box : Shape { public override void Draw() { ... } } class Sphere : Shape { public override void Draw() { ... } } void HandleShape(Shape s) { s.Draw(); ... } HandleShape(new Box()); HandleShape(new Sphere()); HandleShape(new Shape()); // Error!
However, at run-time, if the overloaded method is virtual, then the method that is called is determined by the type of the object
Method overriding is resolved at run-time
Method Versioning in C#
class Base // // v1.0 v2.0 { } public virtual void int Foo() Foo() { Database.Log("Base.Foo"); return 0; } }
v1.0 class Derived : Base // v2.0 { new virtual void void Foo() Foo() public virtual override void Foo() { Console.WriteLine("Derived.Foo"); super.Foo(); } Console.WriteLine("Derived.Foo"); } } }
Instance variables are initialized Base constructor is called Body of constructor is called
class B { private int h; public B() { } public B(int h) { this.h = h; } } class D : B { private int i; public D() : this(24) { } public D(int i) { this.i = i; } public D(int h, int i) : base(h) { this.i = i; } }
Used to clean up any resources held by the instance, do bookkeeping, etc. Only classes, not structs, can have finalizers
class Foo { ~Foo() { Console.WriteLine(Destroyed {0}, this); } }
class Car { string vid; public static bool operator ==(Car x, Car y) { return x.vid == y.vid; } }
+ true
false
! ++
~ --
struct Vector { int x, y; public Vector(x, y) { this.x = x; this.y = y; } public static Vector operator +(Vector a, Vector b) { return Vector(a.x + b.x, a.y + b.y); } ... }
class Note { int value; // Convert to public static return ...; } // Convert to public static return ...; } }
Dont abuse the is operator: it is preferable to design an appropriate type hierarchy with polymorphic methods
More efficient than using is operator: test and convert in one operation Same design warning as with the is operator
Agenda
Review Object-Oriented Concepts Interfaces Classes and Structs Delegates Events
Delegates
Object oriented function pointers
A reference type encapsulating a method signature and return value
Delegate
delegate double Func(double x);
Multicast Delegate
delegate void Greeting();
Agenda
Review Object-Oriented Concepts Interfaces Classes and Structs Delegates Events
Events
Specialized multicast delegate Represent a signal that something has occurred in a program Two main issues
Generating events Consuming events
Events
Overview
C# has native support for events Based upon delegates An event is essentially a field holding a delegate However, public users of the class can only register delegates
They can only call += and -= They cannot invoke the events delegate
Only the object containing the event can invoke the delegate
Multicast delegates allow multiple objects to register with the same event
Events
Create a Type defining the information to be passed to receivers of the event.
public class MailManager { public class MailMsgEventArgs : EventArgs { public readonly string from, to, body; public MailMsgEventArgs(string From, string To, string Body) { this.from = From; this.to = To; this.body = Body;
}
} }
Events
Sourcing
Define the event signature
public delegate void MailMsgEventHandler(object sender, MailMsgEventArgs e);
Events
Create a Method that is responsible for raising the event.
public void SimulateArrivingMsg (string from, string to, string body) { MailMsgEventArgs e = new MailMsgEventArgs(from, to, body);
OnMailMessageReceived(e);
}
Events
Handling
Define and register event handler
public class MyForm: Form { MailManager FaxApplication; public MyForm() { FaxApplication = new MailManager(); FaxApplication.MessageReceived += new MailMsgEventHandler(FaxMsg); } void FaxMsg(object sender, MailMsgEventArgs e) { MessageBox.Show("You recd a msg from + e.from); } }
Attributes
How do you associate information with types and members?
Documentation URL for a class Transaction context for a method XML persistence mapping
Traditional solutions
Add keywords or pragmas to language Use external files, e.g., IDL, DEF
C# solution: Attributes
Attributes
Appear in square brackets Attached to code elements [HelpUrl(http://SomeUrl/Docs/SomeClass)] class SomeClass { [WebMethod] void GetCustomers() { } string Test([SomeAttr] string param1) {} }
Attribute Fundamentals
Can be Intrinsic or Custom Attributes are generic classes!
class HelpUrl : System.Attribute { public HelpUrl(string url) { } }
Creating Attributes
Attributes are simply classes
Derived from System.Attribute Class functionality = attribute functionality
public class HelpURLAttribute: System.Attribute { public HelpURLAttribute(string url) { } public string URL { get { } } public string Tag { get { } set { } } }
Using Attributes
Just attach it to a class
[HelpURL(http://someurl/)] Class MyClass { }
Querying Attributes
Use reflection to query attributes
Type type = typeof(MyClass); foreach(object attr in type.GetCustomAttributes()) { if(attr is HelpURLAttribute) { HelpURLAttribute ha = (HelpURLAttribute) attr; myBrowser.Navigate(ha.URL); } }