C# 中显式转换和安全转换之间的区别
Difference between Explicit conversions and safe cast in c#
第一个运行正常,而第二个显示错误,有什么区别?
我阅读了文档,但没有找到任何相关信息,它不是那么重要但想了解一些功能
public static string GetConcat2<T>(T q)
{
if(q.GetType() == typeof(A))
{
var z = q as A;
}
if (q.GetType() == typeof(A))
{
var z = (A)q;
}
return "!!!!";
}
public interface CustomInteface
{
string InterfaceProperty1 { get; set; }
string InterfaceProperty2 { get; set; }
string Concat();
}
public class A : CustomInteface
{
public string InterfaceProperty1 { get; set; }
public string InterfaceProperty2 { get; set; }
public string Concat() {
return InterfaceProperty1 + InterfaceProperty2;
}
}
行 var z = (A)q;
抛出一个错误,这意味着对象 q
不是 A
类型。您尝试投射的方式也有点尴尬,您应该使用以下模式之一:
as
然后 null
检查:
var z = q as A;
if (z == null) { /*the cast failed*/ }
is
后跟显式转换
if (q is A)
{
var z = (A)q;
}
请注意,如果转换失败,第一个模式将 return null
,而第二个将抛出异常。这就是为什么您只在第二种情况下看到异常,因为第一种情况 "silently" 失败。
第一个运行正常,而第二个显示错误,有什么区别? 我阅读了文档,但没有找到任何相关信息,它不是那么重要但想了解一些功能
public static string GetConcat2<T>(T q)
{
if(q.GetType() == typeof(A))
{
var z = q as A;
}
if (q.GetType() == typeof(A))
{
var z = (A)q;
}
return "!!!!";
}
public interface CustomInteface
{
string InterfaceProperty1 { get; set; }
string InterfaceProperty2 { get; set; }
string Concat();
}
public class A : CustomInteface
{
public string InterfaceProperty1 { get; set; }
public string InterfaceProperty2 { get; set; }
public string Concat() {
return InterfaceProperty1 + InterfaceProperty2;
}
}
行 var z = (A)q;
抛出一个错误,这意味着对象 q
不是 A
类型。您尝试投射的方式也有点尴尬,您应该使用以下模式之一:
as
然后null
检查:var z = q as A; if (z == null) { /*the cast failed*/ }
is
后跟显式转换if (q is A) { var z = (A)q; }
请注意,如果转换失败,第一个模式将 return null
,而第二个将抛出异常。这就是为什么您只在第二种情况下看到异常,因为第一种情况 "silently" 失败。