as(C# 参考)
原文地址:https://msdn.microsoft.com/zh-cn/library/cscsdfbt(v=vs.110).aspx
可以使用 as 运算符执行转换的某些类型在兼容之间的引用类型或 可以为 null 的类型。 下面的代码提供了一个示例。
class csrefKeywordsOperators
{
class Base
{
public override string ToString()
{
return "Base";
}
}
class Derived : Base
{ }
class Program
{
static void Main()
{
Derived d = new Derived();
Base b = d as Base;
if (b != null)
{
Console.WriteLine(b.ToString());
}
}
}
}
class ClassA { }
class ClassB { }
class MainClass
{
static void Main()
{
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;
for (int i = 0; i < objArray.Length; ++i)
{
string s = objArray[i] as string;
Console.Write("{0}:", i);
if (s != null)
{
Console.WriteLine("'" + s + "'");
}
else
{
Console.WriteLine("not a string");
}
}
}
}
/*
Output:
0:not a string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string
*/

浙公网安备 33010602011771号