using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace csrefKeywordsOperators
{
class Base
{
public override string ToString()
{
return "Base";
}
}
class Derived : Base { }
//-------------------------------------------------------
class classA { }
class classB { }
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
Base b = d as Base;
if (b != null)
{
Console.WriteLine(b.ToString());
Console.ReadLine();
}
//--------------------------------------------------------
object[] objArray = new object[6];
objArray[0] = new classA();
objArray[1] = new classB();
objArray[2] = "hello";
objArray[3] = 123;
objArray[4] = 123.4;
objArray[5] = null;
/*The as operator is like a cast operation.
* However, if the conversion isn't possible,
* as returns null instead of raising an exception.
*/
for (int i = 0; i < objArray.Length; i++)
{
string s = objArray[i] as string; // cast operation
Console.WriteLine("{0}:", i);
if (s != null)
{
Console.WriteLine("" + s + "");
}
else
{
Console.WriteLine("not a string");
}
}
Console.ReadLine();
}
}
}
留言列表