c#对象可以动态更改类吗?

时间:2015-07-16 16:31:27

标签: c#

假设我有一个类,其他两个类继承属性。 Computer.cs属性由Desktop.cs和Laptop.cs继承。如果我将Desktop类分配给一个对象,然后需要将它更改为Laptop类的对象,我可以简单地更改类吗?或者我是否需要在每个子类中包含构造函数,这些构造函数知道如何在原始类的新类中创建对象?

实施例: 在表单中,用户选择“桌面”并开始填写来自“计算机”类和“桌面”类的属性的信息。然后,该用户意识到他们打算选择笔记本电脑。 (不知道有人会犯这个错误,所以这是一个愚蠢的例子,我想。)用户在下拉菜单中将他们的选择更改为笔记本电脑。 C#可以处理从对象中删除未继承的属性并添加新类的属性吗?

public class Computer 
{
  public string serial {get; set;} //serial number of PC
}

public class Laptop : Computer
{
  public bool bitlocker {get; set;} //was the laptop bitlockered?
}

public class Desktop : Computer
{
  public bool videoCard {get; set;} //was a video card installed?
}

//just a guess at what it would look like to change pc from Desktop to Laptop class using typecasting
Desktop pc = new Desktop();
Laptop pc = (Laptop)pc;
WriteLine(pc.serial); //returns the serial number set earlier
WriteLine(pc.videoCard); //error: property does not exist
WriteLine(pc.bitlocker); //returns false

写完所有这些之后,SO 突然在2010年发现了一个类似的问题。(How to change the class of an object dynamically in C#?)我怀疑5年后可能会有变化,所以我是无论如何要继续问。

0 个答案:

没有答案