Csharp/C Sharp/Language Basics/as — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 11:39, 26 мая 2010
as operator
using System;
class Employee { }
class ContractEmployee : Employee { }
class CastExample5
{
public static void Main ()
{
Employee e = new Employee();
Console.WriteLine("e = {0}", e == null ? "null" : e.ToString());
ContractEmployee c = e as ContractEmployee;
Console.WriteLine("c = {0}", c == null ? "null" : c.ToString());
}
}
Using the as Keyword to Work with an Interface
using System;
public interface IPrintMessage
{
void Print();
};
class Class1
{
public void Print()
{
Console.WriteLine("Hello from Class1!");
}
}
class Class2 : IPrintMessage
{
public void Print()
{
Console.WriteLine("Hello from Class2!");
}
}
class MainClass
{
public static void Main()
{
PrintClass PrintObject = new PrintClass();
PrintObject.PrintMessages();
}
}
class PrintClass
{
public void PrintMessages()
{
Class1 Object1 = new Class1();
Class2 Object2 = new Class2();
PrintMessageFromObject(Object1);
PrintMessageFromObject(Object2);
}
private void PrintMessageFromObject(object obj)
{
IPrintMessage PrintMessage;
PrintMessage = obj as IPrintMessage;
if(PrintMessage != null)
PrintMessage.Print();
}
}