InvalidCastException 未处理

发布于 2024-12-05 11:40:26 字数 1938 浏览 1 评论 0原文

只是有一个简单的问题...任何帮助将不胜感激!

我正在写一个数据库。我有一个名为“Mechanism”的类,它由另外两个名为“摩托车”和“汽车”的类继承。我将如何根据用户决定输入数据库的内容来打印摩托车或汽车的内容?

这就是我到目前为止所遇到的,它给了我这个错误:InvalidCastException 未处理。无法将类型“ConsoleApplication1.Automobile”的对象转换为类型“ConsoleApplication1.Motorcycle”,

foreach (Mechanism m in mechanisms)
{
    //ptr = m;
    if (flagAuto == true)
    {
        Mechanism ptr = null;
        ptr = m;
        Console.WriteLine("ptr = " + ptr);
        Console.WriteLine("ptr2 = " + ptr2); 
        ptr2 = (Automobile)ptr;
        Console.WriteLine("inside Auto");
        ofp.WriteLine("" + (ptr2.getManufacturer()));
        ofp.WriteLine("" + ptr2.getModel());
        ofp.WriteLine("" + ptr2.getModelYear());
        ofp.WriteLine("" + ptr2.getVIN());
        ofp.WriteLine("" + ptr2.getInitialPurchasePrice());
        ofp.WriteLine("" + ptr2.getPurchaseDate());
        ofp.WriteLine("" + ptr2.getSizeOfEngine());
        ofp.WriteLine("" + ptr2.getTypeOfFuel());
        ofp.WriteLine("" + ptr2.getNumberOfDoors());
        ptr2 = null;
        ptr = null; 
        Console.WriteLine("finishinge Auto");
    }
    else if (flagMotor == true)
    {
        Mechanism ptr = null;
        ptr = m;
        Console.WriteLine("ptr = " + ptr);
        Console.WriteLine("ptr2 = " + ptr1); 
        Console.WriteLine("inside Motor");
        ptr1 = (Motorcycle)ptr;
        ofp.WriteLine("" + ptr1.getManufacturer());
        ofp.WriteLine("" + ptr1.getModel());
        ofp.WriteLine("" + ptr1.getModelYear());
        ofp.WriteLine("" + ptr1.getVIN());
        ofp.WriteLine("" + ptr1.getInitialPurchasePrice());
        ofp.WriteLine("" + ptr1.getPurchaseDate());
        ofp.WriteLine("" + ptr1.getSizeOfEngine());
        ofp.WriteLine("" + ptr1.getTypeOfMotorcycle());
        ptr1 = null;
        ptr = null; 
        Console.WriteLine("finishing Motor");
    }

这些标志应该跟踪尝试将哪种类型的车辆输入到我的数据库中 - 然后它应该将其写入文本文件。 。

Just have a quick question... any help would be greatly appreciate!

I'm writing a database. I have a class called "Mechanism" which is inherited by two other classes called "motorcycle" and "automobile." How would i go about printing the contents of motorcycle or automobile - depending on what the user has decided to enter into the database?

this is what i have so far, it's giving me this error: InvalidCastException was unhandled. Unable to cast object of type "ConsoleApplication1.Automobile" to type "ConsoleApplication1.Motorcycle"

foreach (Mechanism m in mechanisms)
{
    //ptr = m;
    if (flagAuto == true)
    {
        Mechanism ptr = null;
        ptr = m;
        Console.WriteLine("ptr = " + ptr);
        Console.WriteLine("ptr2 = " + ptr2); 
        ptr2 = (Automobile)ptr;
        Console.WriteLine("inside Auto");
        ofp.WriteLine("" + (ptr2.getManufacturer()));
        ofp.WriteLine("" + ptr2.getModel());
        ofp.WriteLine("" + ptr2.getModelYear());
        ofp.WriteLine("" + ptr2.getVIN());
        ofp.WriteLine("" + ptr2.getInitialPurchasePrice());
        ofp.WriteLine("" + ptr2.getPurchaseDate());
        ofp.WriteLine("" + ptr2.getSizeOfEngine());
        ofp.WriteLine("" + ptr2.getTypeOfFuel());
        ofp.WriteLine("" + ptr2.getNumberOfDoors());
        ptr2 = null;
        ptr = null; 
        Console.WriteLine("finishinge Auto");
    }
    else if (flagMotor == true)
    {
        Mechanism ptr = null;
        ptr = m;
        Console.WriteLine("ptr = " + ptr);
        Console.WriteLine("ptr2 = " + ptr1); 
        Console.WriteLine("inside Motor");
        ptr1 = (Motorcycle)ptr;
        ofp.WriteLine("" + ptr1.getManufacturer());
        ofp.WriteLine("" + ptr1.getModel());
        ofp.WriteLine("" + ptr1.getModelYear());
        ofp.WriteLine("" + ptr1.getVIN());
        ofp.WriteLine("" + ptr1.getInitialPurchasePrice());
        ofp.WriteLine("" + ptr1.getPurchaseDate());
        ofp.WriteLine("" + ptr1.getSizeOfEngine());
        ofp.WriteLine("" + ptr1.getTypeOfMotorcycle());
        ptr1 = null;
        ptr = null; 
        Console.WriteLine("finishing Motor");
    }

the flags are supposed to keep track of which type of vehicle is trying to be entered into my database - then it should write it out to a text file..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

善良天后 2024-12-12 11:40:26

这意味着标志的值是错误的。

你应该这样做:

if (m is Automobile)
{
    Automobile autoMobile = m as Automobile;
    //.. work with autoMobile
}
else if (m is Motorcycle)
{
    Motorcycle motorCycle = m as Motorcycle;
    //.. work with motorCycle 
}

顺便说一句,你在两个分支中做同样的事情。这意味着,您可以在基类 (Mechanism) 中实现它们,在 m 对象上调用这些方法。

That means the value of the flag is wrong.

You should do this instead:

if (m is Automobile)
{
    Automobile autoMobile = m as Automobile;
    //.. work with autoMobile
}
else if (m is Motorcycle)
{
    Motorcycle motorCycle = m as Motorcycle;
    //.. work with motorCycle 
}

By the way, you're doing the same thing in the both branch. That implies, that you could implement them in a base class (Mechanism), call those methods on m object.

噩梦成真你也成魔 2024-12-12 11:40:26

并非所有Mechanism都可以转换为Motorcycle。在您的特定情况下,您有一个 Automobile 实例,并且您试图将其转换为 Motorcycle (这就是异常消息所说的内容)。您不能这样做(Dog 无法转换为 Cat,即使两者都是 Animal)。

与其执行逐个类型的逻辑,为什么不直接重写 ToString 或在 Mechanism 上提供一个可以被 Motorcycle 重写的方法> 和汽车。然后您只需调用 ToString 或该方法,而无需担心特定类型。这就是多态性!这是一个帮助您入门的基本示例。

class Mechanism {
     public virtual IEnumerable<string> GetDetails() {
          // assume these are all defined by Mechanism, omitted here for brevity
          yield return this.getManufacturer();
          yield return this.getModel();
          yield return this.getModelYear();
          yield return this.getVIN();
          yield return this.getInitialPurchasePrice();
          yield return this.getPurchaseDate();
          yield return this.getSizeOfEngine();
          yield return this.getTypeOfFuel();
     }
}

class Automobile : Mechanism {
     public override IEnumerable<string> GetDetails() {
          foreach(var detail in base.GetDetails()) {
               yield return detail;
          }
          yield return this.getNumberOfDoors();
     }
}

class Motorcycle : Mechanism {
     public override IEnumerable<string> GetDetails() {
         foreach(var detail in base.GetDetails()) {
             yield return detail;
         }
         yield return this.getTypeOfMotorCycle();
     }
}

然后你就可以说:

foreach(var mechanism in mechanisms) {
    foreach(var detail in mechanism.GetDetails()) {
        ofp.WriteLine(detail);
    }
}

呀,真漂亮!

Not all Mechanism can be cast to Motorcycles. In your particular case, you have an instance of Automobile and you are trying to cast it to a Motorcycle (that's what the exception message says). You can't do that (A Dog can not be converted to Cat even though both are Animal).

Instead of doing type-by-type logic, why don't you just override ToString or provide a method on Mechanism that can be overridden by Motorcycle and Automobile. Then you can just invoke ToString or that method, without evening having to worry about the particular type. That's polymorphism! Here's a rudimentary example to get you started.

class Mechanism {
     public virtual IEnumerable<string> GetDetails() {
          // assume these are all defined by Mechanism, omitted here for brevity
          yield return this.getManufacturer();
          yield return this.getModel();
          yield return this.getModelYear();
          yield return this.getVIN();
          yield return this.getInitialPurchasePrice();
          yield return this.getPurchaseDate();
          yield return this.getSizeOfEngine();
          yield return this.getTypeOfFuel();
     }
}

class Automobile : Mechanism {
     public override IEnumerable<string> GetDetails() {
          foreach(var detail in base.GetDetails()) {
               yield return detail;
          }
          yield return this.getNumberOfDoors();
     }
}

class Motorcycle : Mechanism {
     public override IEnumerable<string> GetDetails() {
         foreach(var detail in base.GetDetails()) {
             yield return detail;
         }
         yield return this.getTypeOfMotorCycle();
     }
}

Then you can just say:

foreach(var mechanism in mechanisms) {
    foreach(var detail in mechanism.GetDetails()) {
        ofp.WriteLine(detail);
    }
}

Aye, it's beautiful!

千と千尋 2024-12-12 11:40:26

好吧,简单地说,您的 flagMotor 在骗您;正如错误消息所示,该对象是 Automobile,但您试图将其转换为 Motorcycle。您需要找出为什么您的标志设置错误。

或者您可以完全消除这些标志,并使用 C# 的 is 运算符:

if (m is Automobile) {
    // ...
} else  if (m is Motorcycle) {
    // ...
}

Well, simply put, your flagMotor is lying to you; the object is an Automobile, as the error message says, but you're trying to cast it to Motorcycle. You need to find out why your flags are set wrong.

Or you could eliminate the flags altogether, and use C#'s is operator:

if (m is Automobile) {
    // ...
} else  if (m is Motorcycle) {
    // ...
}
少女七分熟 2024-12-12 11:40:26

正如 Ernest Friedman-Hill 提到的,在您当前的架构中,标志设置不正确。

可能值得一提的是,(没有看到类的完整源代码),看起来您的对象层次结构可能不太标准 OOP。您可能应该让 Mechanism 类包含从 Mechanism 派生的各个类之间通用的所有成员,并重写两者之间可能不同但在两者中都有意义的任何方法。这也为机制成为抽象基类提供了一个很好的理由。

下面是一个过于简单化的例子:

public class Mechanism {
    public string Vin {get;set;}
}

public class Auto : Mechanism {
    public int NumberOfDoors {get;set;

    public override string ToString() {
        return string.Format("{0}, {1}", Vin, NumberOfDoors);
    }
}

public class Motorcycle : Mechanism {
    public string TypeOfMotorcycle {get;set; }

    public override string ToString() {
        return string.Format("{0}, {1}", Vin, TypeOfMotorcycle );
    }
}

foreach (Mechanism m in mechanisms) {
    Console.Print(m.ToString());
}

As Ernest Friedman-Hill mentions, with your current archetuture, the flags are not being set correctly.

It may be worth mentioning, (not having seen the full source for your classes), it looks like perhaps your object hierarchy isn't quite standard OOP. You should probably have the Mechanism class contain all members that are common between the various classes that derive from Mechanism, and override any methods that may differ between the two but make sense to have in both. This also makes a decent case for Mechanism to be an Abstract Base Class.

A ridiculously over simplified example follows:

public class Mechanism {
    public string Vin {get;set;}
}

public class Auto : Mechanism {
    public int NumberOfDoors {get;set;

    public override string ToString() {
        return string.Format("{0}, {1}", Vin, NumberOfDoors);
    }
}

public class Motorcycle : Mechanism {
    public string TypeOfMotorcycle {get;set; }

    public override string ToString() {
        return string.Format("{0}, {1}", Vin, TypeOfMotorcycle );
    }
}

foreach (Mechanism m in mechanisms) {
    Console.Print(m.ToString());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文