代码之家  ›  专栏  ›  技术社区  ›  Ram

正常排版和使用__作为_关键字[重复]有什么区别?

  •  7
  • Ram  · 技术社区  · 15 年前

    可能重复:
    Direct casting vs 'as' operator?
    Casting: (NewType) vs. Object as NewType

    普通排版和使用__作为_关键字有什么区别?

    8 回复  |  直到 15 年前
        1
  •  18
  •   Bennor McCarthy    15 年前

    as

    object x = new object();
    string y = x as string; // y == null
    string z = (string)x; // InvalidCastException
    
        3
  •  1
  •   Sly    15 年前

    as

    Object a = new Object();
    String b = a as String;
    if(b != null) // always false for this example.
    {}
    
        4
  •  1
  •   Srinivas Reddy Thatiparthy    15 年前

    as null

        5
  •  1
  •   The King    15 年前
    ((Class2) obj)  // Throws exception when the casting cannot be made
    
    Class2 C = obj as Class2  //  Will return NULL if the casting cannot be made
    
        6
  •  0
  •   Cheng Chen    15 年前

    null

    public class A {}
    public class B {}
    ...
    A a = new A();
    //B b = (B)a;  //compile error:Cannot implicitly convert type 'A' to 'B'
    

    implicit explicit

        7
  •  0
  •   Øyvind Bråthen    15 年前

        8
  •  0
  •   Justin    15 年前

    as

    expression as type
    

    expression is type ? (type) expression : (type) null
    

    expression

    is

    uint? u = 52;
    int? i = (int?) u;   // 'i' is now 52
    

    uint? u = 52;
    object d = u;
    int? i = d as int?;
    

    uint? u = 52;
    int? i = (u is int?) ? (int?) u : (int?) null;
    

    “我现在” null

    uint? u = 52;
    int? i = u as int?;
    

    哎呀。编译器错误。所以,我想这两种说法毕竟不完全相同。

    推荐文章