在软件开发中,类型转换是不可避免的事情。在许多情况下,开发人员需要将一个Object(Type)转换为另一个Object(Type),有时他/她可能会收到InvalidCastException。因此,为了克服此类异常,C#提供了运算符关键字。
as运算符用于在兼容引用类型或可空类型之间进行转换。当运算符与给定类型兼容时,此运算符将返回该对象,如果无法进行转换而不是引发异常,则返回null 。作为运算符是非常相似的工作是运算符,但在缩短的方式。
句法:
expression as type
上面的语法与下面的代码等效。但是表达式变量将仅被评估一次。
expression is type ? (type)expression : (type)null
在这里,“是”是运算符关键字。
注意: C#中的’as’运算符关键字仅用于可为空,引用和装箱转换。它不能执行只能通过使用强制转换表达式执行的用户定义的转换。
示例1:在下面的代码中, str1包含一个字符串,该字符串分配给对象类型的变量obj1 。现在,将此obj1使用as运算符为字符串,并将大小写结果分配给字符串类型的变量str2 。如果成功,则返回结果,否则返回null。在此, if(str2!= null)用于检查结果是否为null。对于List < 字符串> mylist = obj1,因为List < 字符串>强制转换失败,并且返回null。
// C# program to illustrate
// the use of 'as' operator
using System;
using System.Text;
using System.Collections.Generic;
class GFG {
// Main Method
public static void Main() {
// taking a string variable
string str1 = "GFG";
// taking an Object type variable
// assigning var1 to it
object obj1 = str1;
// now try it to cast to a string
string str2 = obj1 as string;
// checking Successfully cast or not
if(str2 != null)
{
Console.WriteLine("Successfully Cast");
}
// now try to cast it to List
List mylist = obj1 as List;
// checking Successfully cast or not
if(mylist != null)
{
Console.WriteLine("Successfully Cast");
}
else
{
Console.WriteLine("Not Successfull");
}
}
}
Successfully Cast
Not Successfull
示例2:在代码中,我们采用一个Object数组,该数组可以存储五个元素。第一个和第二个元素是类Geeks1和类Geeks2的实例。第三个元素是字符串,第四个元素是双精度值,第五个元素是空值。在这里,字符串str = obj [j]作为字符串;我们使用as运算符将对象数组转换为字符串并将结果存储到字符串str中。之后,检查结果值。如果为null,则打印“ element not a 字符串”;如果不为null,则打印字符串。
// C# program to illustrate the
// concept of 'as' operator
using System;
// Classes
class Geeks1 { }
class Geeks2 { }
class GFG {
// Main method
static void Main()
{
// creating and initializing object array
object[] obj = new object[5];
obj[0] = new Geeks1();
obj[1] = new Geeks2();
obj[2] = "C#";
obj[3] = 334.5;
obj[4] = null;
for (int j = 0; j < obj.Length; ++j) {
// using as operator
string str = obj[j] as string;
Console.Write("{0}:", j);
// checking for the result
if (str != null) {
Console.WriteLine("'" + str + "'");
}
else {
Console.WriteLine("Is is not a string");
}
}
}
}
0:Is is not a string
1:Is is not a string
2:'C#'
3:Is is not a string
4:Is is not a string