【问题标题】:Dynamic casting of base class to child in c#在c#中将基类动态转换为子类
【发布时间】:2018-12-15 06:46:53
【问题描述】:

我有一个基类和两个子类,其中一个类有额外的字段。该函数将基类作为参数并在运行时将其转换为子类,但将基类转换为 B 类会出错

public class Base {
       int x
  }

public class A :Base {
    A() { x= 5;}
      }
public class B :Base {
   int y ;
   B() { x=5
        y=5;
      }
  }

在运行时将基类转换为子类时,会抛出无效的转换操作错误

public int getValue(Base base) {
      A a = base as A //works fine
      B b = base as B // throws invalid cast opertions
      return (a.x + b.x + b.y)
    }

它应该可以工作,因为这两个类都从基类继承,但无法弄清楚为什么它在 B 类上失败。

为什么会这样?

【问题讨论】:

  • 您可以使用 Base 或 A 的实例调用 getValue,因为 A 是 Base 的子类。你不能用 B 来调用它,因为 B 没有基类,除了objectas 运算符不会抛出,如果强制转换失败,它将简单地返回 null。由于 B 不是 Base 的子类,因此您的 `base as B` 表达式不会编译
  • 另外,如果getValue 接受任何Base,而不仅仅是A 实例,如果你只用Base 实例调用它,base as A 将返回null,所以a.x如果可以编译并且您将其基于Base,则会抛出
  • 要么您的示例与您的问题不匹配,要么您忘记从 B 类中的 Base 类继承。
  • public class B : { 是无效代码 - 请检查您发布的内容(请参阅 minimal reproducible example 发布代码指南)。假设 public class B : Base { ... 作为您的帖子声称您不应该收到您声称的错误...
  • @AlexeiLevenkov 是的,我已经编辑过了

标签: c# exception casting


【解决方案1】:

这很符合逻辑,只有当基类的实例是B类时,才能进行强制转换。我做了一个小例子来更好地解释这一点:

public class BaseClass
  {
    public int x { get; set; }
  }

public class A : BaseClass
{
    public A() { x = 5; }
}
public class B : BaseClass {
    public int y { get; set; }
    public B()
        {
            x = 5; y = 5;
        }
    }
class Program
{
        static void Main(string[] args)
    {
        BaseClass bClase = new BaseClass();
        A a = bClase as A; //a = null
        B b = bClase as B; // c = null

        BaseClass bClase2 = new A();
        A a2 = bClase2 as A; //works fine
        B b2 = bClase2 as B; // b2 = null

        BaseClass bClase3 = new B();
        A a3 = bClase3 as A; // b2 = null
        B b3 = bClase3 as B; //works fine
        //Cast down = ok
        BaseClass bb = bClase3 as BaseClass;

    }
}

PS:为了将来使用stackoverflow,请提供工作代码。让您的助手生活得更轻松。

【讨论】:

    猜你喜欢
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多