一、C# as运算符
as运算符用于执行引用类型的显式类型转换。请阅读C#数据类型。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// C# as运算符-www.baike369.com
object obj1 = "this is a string";
object obj2 = 9;
string str1 = obj1 as string; // 转换成功
Console.WriteLine("str1:" + str1);
string str2 = obj2 as string; // 转换失败
Console.WriteLine("str2:" + str2);
Console.ReadLine();
}
}
}
运行结果:
str1:this is a string
str2:
str2返回null。
注:如果要转换的类型与指定的类型兼容,就会成功转换;如果要转换的类型与指定的类型不兼容,as运算符就会返回null值。
在C#中,as运算符用于在兼容的引用类型之间执行安全的转换,或者在调用对象的实例和接口之间执行转换。如果转换不可能,as运算符会返回null。
下面是as运算符的一些常见用法:
在引用类型之间转换:
object obj = "Hello as operator";
string str = obj as string;
if(str != null)
{
Console.WriteLine(str);
}
else
{
Console.WriteLine("obj is not a string");
}
在上述代码中,我们尝试将object类型的obj转换为string类型。如果obj确实是一个字符串,那么str将指向相同的字符串实例,并且转换成功。如果obj不是字符串,那么str将为null,并且转换失败。
在类和其实现的接口之间转换:
public interface IExample
{
void DoSomething();
}
public class MyClass : IExample
{
public void DoSomething()
{
Console.WriteLine("Doing something");
}
}
public class Program
{
public static void Main()
{
MyClass myClass = new MyClass();
IExample example = myClass as IExample;
if(example != null)
{
example.DoSomething();
}
}
}
在上述代码中,我们创建了一个类MyClass,该类实现了接口IExample。然后我们尝试将MyClass的实例转换为IExample。由于MyClass实现了IExample,因此转换成功,并且example将指向MyClass的实例。
在使用as运算符时,还需要进行null检查,因为as运算符永远不会抛出异常,但是如果转换失败,它会返回null。