is
C#中允许数据在继承链中向下转型,在转换前需要判断数据的类型,可以使用is来判断基础类型。可以这样来理解:若该对象可以非空,且可以强制转换为所提供的类型而不引发异常,则is表达式返回true。使用语法为:
if(obj is objType)
{
}
若obj为null则返回false;
/// <summary>
/// 判断是否为string
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static bool IsString(object data)
{
bool result = false;
if (data is string)
result = true;return result;
}
在上述示例中,实际上CLR会对data进行两次类型检查:首先检查data所引用的对象是否和string兼容;若兼容则有if语句内CLR在执行转换时又会检查data是否为string类型的引用。
object dat1="String";
bool result1 = IsString(dat1);
object dat2 = 23;
bool result2 = IsString(dat2);
object dat3 = null;//空数据
bool result3 = IsString(dat3);
Console.WriteLine(result1.ToString());
Console.WriteLine(result2.ToString());
Console.WriteLine(result3.ToString());
运行结果为

as
在之前一节的类型转换提到了各种类型转换,还有一种转换方式使用as运算符进行转换,as将对象转换为一个特定的数据类型。若转换失败,as运算符会将null值赋给目标,这样就避免了可能因为转型而造成的异常。在msdn有as 的一个经典示例。
class Class1
{
}class Class2
{
}class MainClass
{
static void Main()
{
object[] objArray = new object[6];
objArray[0] = new Class1();
objArray[1] = new Class2();
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");
}
}
}
}
运行结果:

Related posts:
以上关联文章由 Yet Another Related Posts Plugin 提供支持。
Leave a reply