【问题标题】:C# - Inherited method passing self objectC# - 传递 self 对象的继承方法
【发布时间】:2016-03-26 07:07:00
【问题描述】:

真正的问题在于反射和装配修补/挂钩。我将举一个简单的例子来展示我的问题,而不会太难理解主要问题。

假设我有这些基本类:

public class Vehicle
{
    public string Name;
    public string Price;

    public void DoSomething()
    {
        Main.Test(this);
    }
}

public class Car : Vehicle
{
    public int Wheels;
    public int Doors;
}

我在主代码上运行它:

public class Main
{
    public void Start()
    {
        Car testCar = new Car()
        {
            Name = "Test Car",
            Price = "4000",
            Wheels = 4,
            Doors = 4
        };

        testCar.DoSomething();
    }

    public static void Test(Vehicle test)
    {
        // Is this allowed ?
        Car helloWorld = (Car) test;
    }   
}

好的,问题是:

是否允许进行强制转换(在静态方法测试中)?我会失去 Car 属性但保留 Vehicle 属性吗?

万一出错了,还有其他办法吗?

谢谢。

【问题讨论】:

  • "万一出错了,有没有其他办法呢?"做什么?
  • 欢迎来到 Stack Overflow。那应该是相对容易测试的东西。那你试过了吗?如果不是,那是提出问题的先决条件。如果有,您是否遇到了具体问题?
  • @IvanStoev 将对象作为汽车而不是车辆。
  • 如果是Truck 怎么办?我的意思是,假设你有另一个类Truck : Vehicle,你怎么知道Vehicle testCar 而不是Truck 或任何其他Vehicle 派生类

标签: c#


【解决方案1】:

仅当传入的对象恰好是Car 时,才允许将Vehicle 转换为Car。否则你会得到一个异常。

有一个类型错误时不会引发异常的强制转换:

Car car = test as Car;

这永远不会抛出,但是当Vehicle 不是 Car 时,变量car 将是null。您可以添加一个if 条件来测试转换是否成功:

Car car = test as Car;
if (car != null) {
    ...
}
Bus bus = test as Bus;
if (bus != null) {
    ...
}
Rv rv = test as Rv;
if (rv != null) {
    ...
}

不过,C# 提供了一个更好的解决方案:方法重载可以让您完全避免强制转换。

public class Main {
    public static void Test(Car test) {
        ... // This method will be called by Main.Test(this) of a Car
    }
    public static void Test(Bus test) {
        ... // This method will be called by Main.Test(this) of a Bus
    }
    public static void Test(Rv test) {
        ... // This method will be called by Main.Test(this) of an Rv
    }
}

这是可行的,因为当您调用 Main.Test(this) 时,编译器知道 this 变量的确切类型。

【讨论】:

  • 这就是我想要的。感谢您的回答!
【解决方案2】:

是的,演员表是允许的,你不会“失去”任何属性。但如果Vehicle test 实际上不是Car 的一个实例,那么你的演员将抛出一个InvalidCastException

【讨论】:

  • 感谢您的回答!
【解决方案3】:

是的,这是允许的。它被命名为downcasting

请记住,可以通过类型自省来检查被引用对象的类型是否确实是被强制转换的类型或它的派生类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-27
    • 2012-03-28
    • 1970-01-01
    • 2013-01-04
    • 2016-08-10
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    相关资源
    最近更新 更多