2017-04-27 102 views
-1

第一个工作正在进行,而第二个显示错误,有什么区别? 我阅读文档,并没有发现任何关于它,它不是那么重要,但要知道的一些功能显式转换和安全转换之间的差异#

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; 
    } 
} 
+0

什么是错误,它在哪里抛出错误?尝试提供重现问题所需的所有信息和代码,包括[MCVE]。 – TheLethalCoder

+0

@ TheLethalCoder var z =(A)q; 这里有一个错误,它无法强制类型A – GodlikeRabbit

回答

1

线var z = (A)q;抛出一个错误,这意味着该对象qA类型的不行。你想投的方式是有点尴尬,以及你应该使用下列模式之一:

  • as其次null检查:

    var z = q as A; 
    if (z == null) { /*the cast failed*/ } 
    
  • is其次是明确的转换

    if (q is A) 
    { 
        var z = (A)q; 
    } 
    

注意f如果转换失败,第一个模式将返回null,第二模式将抛出异常。这就是为什么你只能在第二种情况下看到例外情况,因为第一种情况是“默默”失败。

+0

,因为你可以看到,我检查通用类型,所以它必须是正确的类型 if(q.GetType()== typeof(A)) – GodlikeRabbit

+0

@GodlikeRabbit是但不要这样做,请尝试以适当的方式进行。同时调试你的应用程序,看看实际是什么'q'。 – TheLethalCoder