当我们处理强制转换时,在某些情况下可能会抛出异常。例如,如果内存中对象的类型与强制转换不匹配,则运行时将引发 System.InvalidCastException。例如:
class Program
{
static void Main(string[] args)
{
Object obj = new Car();
var bus = ((Bus)obj); // This will throw a System.InvalidCastException;
var b = (int) obj; // This will throw a System.InvalidCastException;
}
}
此代码将编译,但会在运行时引发异常。为了避免这种错误,我们可以使用 C# 提供的 and 运算符,它可以帮助我们以更优雅的方式执行强制转换操作。isas
is 运算符
运算符用于检查对象的运行时类型是否与给定类型兼容。验证结果将返回一个布尔值(true 或 false),并且 is 运算符永远不会引发异常。例:is
class Program
{
static void Main(string[] args)
{
Person person = new Person();
Boolean b1 = (person is Person); // this will return true;
Boolean b2 = (person is Employee); // this will return false;
}
}
当使用 is 运算符检查对象是否与特定类型匹配时,如果类型不同,则不会抛出异常。例:
class Program
{
static void Main(string[] args)
{
Object obj = new Car();
if (obj is Bus)
Console.WriteLine("Entered here - Bus"); // This will not be printed and will not throw an exception;
if (obj is 0)
Console.WriteLine("Entered here - 0"); // This will not be printed and will not throw an exception;
if (obj is "value")
Console.WriteLine("Entered here - value"); // This will not be printed and will not throw an exception;
if (obj is Car)
Console.WriteLine("Entered here - Car"); // This will be printed;
}
}
如果对象的引用为 null,则运算符 it 将始终返回 false,因为没有对象可用于检查其类型。is
这些是运算符的规范:is
运算符的一个问题是,当您检查它时,然后也将其转换为该类型的实例。这样做的问题在于,在“幕后”,操作员使用演员来做出决定。在下面的示例中,有两个单独的强制转换,第一个在 上,第二个在显式强制转换上:
class Program
{
static void Main(string[] args)
{
Object obj = new Car();
if (obj is Car) // The first cast to check
{
((Car) obj).Run(); // The second cast - the explicit cast
}
}
}
如果我们不需要这样做,就没有必要投两次。因此,对于这种情况,更好的方法是使用带有变量的运算符,例如:
class Program
{
static void Main(string[] args)
{
Object obj = new Car();
if (obj is Car car)
{
car.Run();
}
}
}
在此示例中,仅发生一次强制转换。另一个好方法是使用运算符。as
as 运算符
运算符用于显式将值转换为给定的引用类型或可为 null 的类型。运算符从不抛出异常,如果无法转换,它将返回 null。例:
class Program
{
static void Main(string[] args)
{
Object obj = new Car();
Car car = obj as Car;
if (car != null)
Console.WriteLine("Entered here"); // This will be printed;
Object obj2 = new Bus();
Car car2 = obj2 as Car;
if (car2 != null)
Console.WriteLine("Entered here"); // This will not be printed;
}
}
在此示例中,我们对每个代码块只有一个强制转换,并且此方法还允许您避免在执行时可能发生的任何异常。
这些是运算符的规范:as
和运算符是进行对象投射的两种好方法,它们还可以帮助我们避免在投射过程中出现故障时出现异常。只是需要注意的是,有时与其使用转换,不如使用多态性来解决某些问题,例如,如果你对不同类型的进行多次检查,做大量的强制转换,然后调用这些类型的方法,你应该考虑使用多态性是否更好。