【问题标题】:Typecasting an object in C#在 C# 中对对象进行类型转换
【发布时间】:2015-10-10 01:11:00
【问题描述】:

假设我有一个返回类 A 对象的方法

A getItem(int index)

现在我有以下代码行,(我假设 BA 的子类)

B b = (B) obj.getItem(i);

但在此之前,我必须确保我可以将其类型转换为 B,因为 getItem 可以返回 A 的某个其他子类的对象,例如 C

类似的东西

    if(I can typecast obj.getItem(i) to B) {
             B b = (B) obj.getItem(i);
    }

我该怎么做?

【问题讨论】:

标签: c#


【解决方案1】:

两种选择:

object item = obj.getItem(i); // TODO: Fix method naming...
// Note: redundancy of check/cast
if (item is B)
{
    B b = (B) item;
    // Use b
}

或者:

object item = obj.getItem(i); // TODO: Fix method naming...
B b = item as B;
if (item != null)
{
    // Use b
}

请参阅"Casting vs using the 'as' keyword in the CLR" 了解两者之间的更详细比较。

【讨论】:

    【解决方案2】:
    var item = obj.GetItem(i);
    if(item is B) {
       B b = (B) item;
    }
    

    【讨论】:

      【解决方案3】:

      改用as

      B b = obj.getItem(i) as B;
      if(b != null)
          // cast worked
      

      as 运算符类似于强制转换操作。但是,如果无法进行转换,as 将返回 null 而不是引发异常

      【讨论】:

        【解决方案4】:

        试试as 关键字。见https://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

        Base b = d as Base;
        if (b != null)
        {
           Console.WriteLine(b.ToString());
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多