interface :
[ ] interface _
{
//
}
I. , , :
public interface I_Researcher
{
void Investigate();
void Invent();
}
C# . , . , . . , , .
:
public interface I_Task {
String Description {get;}
void perform();
}
public class SynopticsTask: I_Task {
private readonly String description = "Load synoptics data for some region";
private readonly String city;
public SynopticsTask(String city) {
this.city = city;
}
public void perform() {
// TODO: connect to internet, parse response, print results.
}
public String Description {
get {return description;}
}
}
public class CleanupTask: I_Task {
public void perform() {
//TODO: Recursive search for folders 'Temp', 'tmp', clean up them.
}
public String Description {
get { return "Task for removing all temporary files on disk"; }
}
}
class Program
{
public static void Main(string[] args) {
var tasks = new I_Task[] {new SynopticsTask("ZP"), new CleanupTask()};
foreach (I_Task task in tasks) {
Console.WriteLine(task.Description);
task.perform();
}
}
}
:
Load synoptics data for some region
Task for removing all temporary files on disk
, . , .
, :
public interface I_Human
{
object Work();
}
public interface I_Inferior
{
object Work();
}
, . , .
public class Employee: I_Human, I_Inferior
{
// I_Human
object I_Human.Work() {...}
// I_Inferior
object I_Inferior.Work() {...}
}
: Work() Employee, ?
, . :
// Employee:
Employee john = new Employee();
I_Human human = john;
|
|
human.Work(); // I_Human.Work
I_Inferior inferior = john;
inferior.Work(); // I_Inferior.Work
, , as. , , , null. , null.
:
IInfo obj = ui1 as IInfo;
if (obj!= null)
Console.WriteLine(" UI IInfo");
else
Console.WriteLine(":(");
, , is. , false, , try/catch.
:
if (ui1 is IInfo)
Console.WriteLine(" UI IInfo");
else
Console.WriteLine(":(");
IEnumerable ( )
GetEnumerator | , . |
ICollection ( IEnumerable, )
Count | , . |
IsSynchronized | , true, ICollection (), false. false |
CopyTo(Array array, int index) | ICollection array, Array index. |
IList ( ICollection, )
int Add(object value) | value. , . |
void Clear() | . |
bool Contains(object value) | true, value . false. |
int IndexOf(object value) | value . |
void Insert(int index, object value) | value . |
void Remove(object value) | value . |
void RemoveAt(int index) | , (index). |
bool IsFixedSize | , true, . -false. |
bool IsReadOnly | true, . false. |
object Item[int index]{get;set;} | . |
IDisposable ( . )
void Dispose() | , . |
IComparable ( . , , )
int CompareTo(object obj) | , , , , . |
:
|
|
public class Student: IComparable<Student> {
private String name;
private String group;
private float avgScore;
public Student(String name, String group, float avgScore) {
this.name = name;
this.group = group;
this.avgScore = avgScore;
}
public String Name {
get {return name;}
}
public String Group {
get {return group;}
}
public float AvgScore {
get {return avgScore;}
}
public int CompareTo(Student compareStudent) {
// A null value means that this object is greater.
if (compareStudent == null)
return 1;
else
return this.name.CompareTo(compareStudent.name);
}
}
Student[] studentArray = new Student[5];
studentArray[0] = new Student("Ivanov", "510", 4.7f);
studentArray[1] = new Student("Petrov", "510", 3.7f);
studentArray[2] = new Student("Sobolev", "530", 4.2f);
studentArray[3] = new Student("Smirnov", "530", 5.0f);
studentArray[4] = new Student("Sidorov", "520", 4.0f);
List<Student> studentList = new List<Student>();
//foreach over IEnumerable interface
foreach(Student student in studentArray) {
Console.WriteLine(student.Name);
studentList.Add(student);
}//Ivanov Petrov Sobolev Smirnov Sidorov
studentList.Sort(); //Sort alphabetically using Student.CompareTo()
foreach(Student student in studentList) {
Console.WriteLine(student.Name);
}
//Ivanov Petrov Sidorov Smirnov Sobolev
10
C# . , , .
abstract.
, .
- .
:
// ,
public abstract class MobilePhone {
protected void sendMessage(String message, String phoneNumber) {
//check GSM connection
//check balance
//send sms
//handle response success/failed
Console.WriteLine("You have send '" + message + "' from " + phoneNumber);
}
protected void performCall(String phoneNumber, String myPhone) {
//init Call
//handle call lifecycle
Console.WriteLine("You have performe call to " + phoneNumber + " from " + myPhone);
}
protected String getDefaultPhoneNumber() {
return "066-550-94-88";
}
}
//
public class ButtonMobilePhone: MobilePhone {
private String input;
// . 0-9 input .
// call .
public void handleButton(String buttonType) {
switch (buttonType) {
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9": //
input += buttonType;
break;
case "cancel": // , input
input = "";
case "call": //
performCall(input, getDefaultPhoneNumber());
break;
}
}
}
//Andoird , MobilePhone
public class AndroidMobilePhone: MobilePhone {
|
|
//
public void handleIntent(String type, String extra) {
switch(type) {
case "sendMessage": // ( )
sendMessage(extra, getDefaultPhoneNumber());
break;
case "initCall": // ( )
performCall(extra, getDefaultPhoneNumber());
break;
}
}
}
//Android
public class DualSimAndroidPhone: AndroidMobilePhone {
private readonly String PHONE_1 = "066-550-94-88";
private readonly String PHONE_2 = "099-005-16-22";
//
private int currentPhone = 1;
//
public void handleIntent(String type, String extra) {
switch(type) {
case "switchPhone": //
if (currentPhone == 1) {
currentPhone = 2;
} else {
currentPhone = 1;
}
break;
default:// -
//AndroidMobilePhone.handleIntent(); - 'sendMessage' 'initCall'
base.handleIntent(type, extra);
}
}
// MobilePhone.getDefaultPhoneNumber()
protected String getDefaultPhoneNumber() {
if (currentPhone == 1) {
return PHONE_1;
}
return PHONE_2;
}
}
, . . , . virtual Human Work(), - Manager, Tutor, Student .. .
- .
.
, , , .
- :
, , ;
, .
( ) , .
-, override.
:
public abstract class AliveCreature {
public virtual void action() {
//perform tipical actions for creature
}
protected virtual void die() {
//clean up resources & object
}
}
public class Plant: AliveCreature {
public override void action() {
// /
//
}
}
public class Bird: AliveCreature {
public override void action() {
//
}
}
public class Human: AliveCreature {
public override void action() {
//
}
}
public class Student: Human {
public override void action() {
//
}
}
sealed
, . . sealed. :
|
|
public sealed class Tutor: Human { }
Tutor. . Tutor .
. virtual, . Work() Human.
class Human
{
public virtual void Work()
{
// Do something
}
}
Employee Work() .
public class Employee: Human
{
public sealed override void Work()
{
// Do something great
}
}
11
C#.NET .
, . , , ( , ), , .
struct:
struct :
{
//
}
, , , , , , .
:
struct Car {
private string model;
private float fuel;
public Car(string model) {
this.model = model;
this.fuel = 0f;
}
public Car(string model, float fuel) {
this.model = model;
this.fuel = fuel;
}
public float Fuel {
get {
return fuel;
}
}
public void run(long distance) {
//calculate fuel based on passed distance
fuel -= distance / 100 * 7;
}
}
, .
struct . , , , , .
.
.
, , , . ( : ).
System.ValueType.
.
System.Object, . . . , .
. , new , : .
. , .
(enumeration) . , . System.Enum.
enum, :
enum EnumName {elem1, elem2, elem3, elem4}
.
. , 0, . .
.
:
enum Action {
INITIAL, LOAD_INPUTS, PARSE_INPUTS, PERFORM_CALCULATIONS, SAVE_OUTPUTS, FINISHED
}
class Task {
private Action state = Action.INITIAL;
|
|
public void perform() {
while (state!= Action.FINISHED) {
performCurrentState();
Console.WriteLine("Current state is " + state);
}
}
private void performCurrentState() {
switch(state) {
case Action.INITIAL:
//init task state
state = Action.LOAD_INPUTS;
break;
case Action.LOAD_INPUTS:
//loading input information
state = Action.PARSE_INPUTS;
break;
case Action.PARSE_INPUTS:
//transforming inputs
state = Action.PERFORM_CALCULATIONS;
break;
case Action.PERFORM_CALCULATIONS:
//core calculations
state = Action.SAVE_OUTPUTS;
break;
case Action.SAVE_OUTPUTS:
//writing results
state = Action.FINISHED;
break;
case Action.FINISHED:
//clear temp information
break;
}
}
}
:
Current state is LOAD_INPUTS
Current state is PARSE_INPUTS
Current state is PERFORM_CALCULATIONS
Current state is SAVE_OUTPUTS
Current state is FINISHED
, . :
- , , . , , ;
- , , ;
- , System.Enum, (CompareTo(), Equals(), GetName(), getValues(), Parse()...).
, . . , .
delegate. , :
delegate Type DelegateName(list)
Type , DelegateName , list ,
( , , ).
, Type list. . , . :
public, protected, private, internal, protected internal.
:
private struct Person {
public String FirstName;
public String LastName;
public DateTime BirthDay;
public Person(String firstName, String lastName, DateTime birthDay) {
this.FirstName = firstName;
this.LastName = lastName;
this.BirthDay = birthDay;
}
public override String ToString() {
return String.Format(": {0}; : {1}; : {2:d}.", FirstName, LastName, BirthDay);
}
public static String GetTypeName() { return ""; }
}
private delegate string GetAsString();
static void Main(string[] args) {
DateTime birthDay = new DateTime(1978, 2, 15);
Person person = new Person("", "", birthDay);
GetAsString getStringMethod =
new GetAsString(birthDay.ToLongDateString);
Console.WriteLine(getStringMethod());
getStringMethod = person.ToString;
Console.WriteLine(getStringMethod());
getStringMethod = Person.GetTypeName;
Console.WriteLine(getStringMethod());
}
:
15 1978 .
: ; : ; : 15.02.1978.
12
.NET .
, . , ..
, .
, . - , . , . . , . , - . . , , .
. - , - - . -, . .
event:
event DelegateName EventName;
DelegateName ; EventName .
, - , -. , ( ) . , null, .
, void . -, ( object), , EventArgs.
:
public class Person {
public event EventHandler WorkEnded;
public String FirstName;
public String LastName;
public DateTime Birthday;
public Person(String firstName, String lastName, DateTime birthday) {
this.FirstName = firstName;
this.LastName = lastName;
this.Birthday = birthday;
}
public void Work() {
// Do something
if (WorkEnded!= null) WorkEnded(this, EventArgs.Empty);
}
}
static void Person_WorkEnded(object sender, EventArgs e) {
Console.WriteLine(" ! \n");
}
static void Main(string[] args) {
Person person = new Person("Bill", "Gordon", new DateTime(1962, 8, 11));
person.WorkEnded += new EventHandler(Person_WorkEnded);
person.Work();
}
EventHandler .
, - - , . , , .
. , , , . , . System.Array , , , , .
.NET , , . ? . .NET , . , , . , . System.Collections.ArrayList, System.Collections.Queue, System.Collections.Stack, System.Collections.BitArray, ( ) , , , System.Collections.SortedList, System.Collections.Hashtable.
System.Collections.
System.Collections. ArrayList class , , . :
ArrayList arr = new ArrayList();
, . ArrayList , . Capacity:
Console.WriteLine("Capacity: {0}", arr.Capacity);
, :
ArrayList arr1 = new ArrayList(5);
Console.WriteLine("Capacity: {0}", arr1.Capacity);
// Capacity: 5
ArrayList . 4 . ArrayList null . Count .
System.Collections. Stack class , . , , . LIFO (last-infirst-out).
. , :
Stack s = new Stack();
s.Push("one");
s.Push("two");
s.Push("three");
s.Pop();
, , Peek (), , Pop():
System.Collections. Queue class Stack FIFO (first-in-first-out), . , , . . :
Queue q = new Queue();
Enqueue () Dequeue () .
Queue q = new Queue();
for (int i = 1; i < 3; i++) {
q.Enqueue(i);
}
System.Collections. SortedList class -, .
SortedList list = new SortedList();
list.Add(2, 20);
list.Add(1, 100);
list.Add(3, 3);
foreach (int i in list.GetKeyList())
Console.WriteLine(i);
foreach (int i in list.GetValueList())
Console.WriteLine(i);
//1
//2
//3
//100
//20
//3
, , SortedList . Remove (), RemoveAt ().
System.Collections. Hashtable class , -, Object, , , . ( ), .
:
Hashtable hash = new Hashtable();
hash.Add(1, "one");
hash.Add(2, "two");
hash.Add("three", 3);
, , :
1. System.Collections.Specialized. ListDictionary class Hashtable, 10 . .
2. System.Collections.Specialized. HybridDictionary class , ListDictionary Hashtable. . ListDictionary , 10 , Hashtable. Hashtable, ListDictionary , 10 . string , . .
3. System.Collections.Specialized. CollectionsUtil class , . 2 : Hashtable, - SortedList.
4. System.Collections.Specialized. NameValueCollection class , string. , .
5. System.Collections.Specialized. StringCollection class string. null . . .
6. System.Collections.Specialized. StringDictionary class Hashtable, string. , , , . null, .
13
MDI