C#:如何确定一般对象实例的某些对象类型

Meg*_*att 0 c# generics inheritance

我需要概述一些上下文的背景信息.请耐心等待,我会尽量简化我的问题:

我有一个继承自另一个对象的对象.我们将第一个对象称为Fruit,第二个称为Apple.所以我宣布苹果如下:

public class Apple : Fruit
{
    public string appleType;
    public string orchardLocation;
    // etc.
}
Run Code Online (Sandbox Code Playgroud)

而Fruit对象如下:

public class Fruit
{
    public int fruitID;
    public int price;
    // etc.
}
Run Code Online (Sandbox Code Playgroud)

所以Apple继承了Fruit.让我们说我有许多其他水果类型都继承自水果:香蕉,橙子,芒果等.

在我的应用程序中,我保持在Session中存储特定类型的水果作为该类型的对象的能力,因此我可能在那里有一个Apple对象或Banana对象.我有一个方法将从会话中检索当前的Fruit,如下所示:

protected Fruit GetModel(int fruitID)
{
   // code to retrieve the fruit from the Session
   // fruitID could be the ID for an Apple or Banana, etc.
}
Run Code Online (Sandbox Code Playgroud)

偶尔,我需要从Session中获取结果,更新一些内容,然后将其上传回Session.我可以这样做:

Apple myApple = (Apple)GetModel(fruitID);
myApple.orchardLocation = "Baugers";
UpdateModel(myApple); // just overwrites the current fruit in the Session
Run Code Online (Sandbox Code Playgroud)

现在我的问题.我需要从Session中提取对象,更新特定于水果本身的东西(比如价格),然后将同一个对象上传回Session.到现在为止,我一直都知道对象的类型,所以在我的情况下 - 如果我知道水果类型 - 我可以说:

Apple myApple = (Apple)GetModel(fruitID);
myApple.price = "4";
UpdateModel(myApple);
Run Code Online (Sandbox Code Playgroud)

但是这一次,我试图让它更加通用于Fruit本身而且并不总是知道孩子的类型.如果我试图从Session中拉出Fruit对象(没有强制转换),更新它,然后重新上传,我现在只丢失了我的子对象(Apple)并且在Session中只有一个Fruit对象.所以我需要一种方法,一般来说,在Session中创建一个对象类型的新实例,更新它,然后重新上传.

我知道一个名为GetType()的.NET方法,它返回一个System.Type,它是你调用它的对象类型,假设该对象继承自Object.但是我无法在这方面走得很远,而且我宁愿不让Fruit从Object继承.

所以我将以我想要的伪代码版本结束:

public updateModelPrice(int price, fruitID)
{
    FigureOutType fruit = (FigureOutType)GetModel(fruitID);
    fruit.price = price;
    UpdateModel(fruit);
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感谢.谢谢.

Jef*_*nal 5

既然price是其成员Fruit,您不需要弄清楚子类型.你可以这样做:

public updateModelPrice(int price, fruitID)
{
    Fruit fruit = GetModel(fruitID);
    fruit.price = price;
    UpdateModel(fruit);
}
Run Code Online (Sandbox Code Playgroud)

  • @Matt - 转换对象实例不会改变底层实例的类型:它仍然是一个"Apple",在代码的其他部分,你仍然可以通过再次强制转换它来将实例视为"Apple". (2认同)