简体   繁体   English

C# 中的对象转换

[英]Object Casting in C#

what is the difference as well as the pros and cons between有什么区别以及优缺点

 LinkButton lb = (LinkButton)ctl;

and

 LinkButton lb = ctl as LinkButton;

I tried using the first one and it gives me error, then I tried the other one with the keyword as, it work just fine.我尝试使用第一个,但它给了我错误,然后我用关键字 as 尝试了另一个,它工作得很好。

Thank You in Advance.先感谢您。

The first is an explicit cast, and the second is a conversion.第一个是显式转换,第二个是转换。 If the conversion fails for the as keyword, it will simply return null instead of throwing an exception.如果as关键字的转换失败,它将简单地返回null而不是抛出异常。

This is the documentation for each:这是每个的文档:

Note in the linked documentation above, they state the as keyword does not support user-defined conversions.请注意,在上面的链接文档中,他们声明as关键字不支持用户定义的转换。 +1 to Zxpro :) This is what a user-defined conversion is: +1 到 Zxpro :) 这就是用户定义的转换:

User-Defined Conversions Tutorial用户定义的转换教程

My usual guidance on using the as operator versus a direct cast are as follows:我对使用as运算符与直接强制转换的通常指导如下:

  1. If the cast must succeed (ie it would be an error to continue if the cast failed), use a direct cast.如果强制转换必须成功(即,如果强制转换失败,继续执行将是错误的),请使用直接强制转换。
  2. If the cast might fail and there needs to be programmatic detection of this, use the as operator.如果强制转换可能失败并且需要对此进行编程检测,请使用as运算符。

The above is true for reference types.以上适用于引用类型。 For value types (like bool or int ), as does not work.对于值类型(如boolint ), as不起作用。 In that case, you will need to use an is check to do a "safe cast", like this:在这种情况下,您需要使用is检查来执行“安全转换”,如下所示:

if (x is int y)
{
   // y is now a int, with the correct value

}
else
{
    // ...
}

I do not recommend trying to catch InvalidCastException , as this is generally the sign of a programmer error.我不建议尝试捕获InvalidCastException ,因为这通常是程序员错误的标志。 Use the guidance above instead.请改用上述指南。

I believe that casting using the first method throws an exception if it can't cast the object properly (trying to cast the wrong type), whereas using the as keyword will simply set the variable to null if it couldn't cast it properly.我相信,如果使用第一种方法无法正确转换对象(尝试转换错误类型),则使用第一种方法进行转换会引发异常,而如果无法正确转换,则使用 as 关键字只会将变量设置为 null。

So make sure that if you use the as keyword cast, you check因此,请确保如果您使用 as 关键字强制转换,请检查

if(lb == null)
    return null; // or throw new Exception()

and if you use the () cast, you surround it with如果你使用 () 演员表,你用

try
{
    LinkButton lb = (LinkButton)ctl;
}
catch(InvalidCastException ex)
{
    //TODO: Handle Exception
}

The second one is called safe cast, which, instead of throwing exception, will put "null" to your variable.第二个称为安全转换,它不会抛出异常,而是将“null”放入您的变量中。 So it does NOT work fine, but sets your LinkButton lb to null所以它不能正常工作,但将您的LinkButton lb为 null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM