我想在c#中创建一个可以扩展到子类的基类。C#对象继承
例如:
public class ObjectsInTheSky
{
public string Size, Shape;
public float Mass;
public int DistanceFromEarth;
public bool hasAtmosphere, hasLife;
public enum ObjectTypes {Planets,Stars,Moons}
public ObjectsInTheSky(int id)
{
this.Load(id);
}
public void Load(int id)
{
DataTable table = Get.DataTable.From.DataBase(id);
System.Reflection.PropertyInfo[] propInfo = this.GetType().GetProperties();
Type tp = this.GetType();
foreach (System.Reflection.PropertyInfo info in propInfo)
{
PropertyInfo p = tp.GetProperty(info.Name);
try
{
if (info.PropertyType.Name == "String")
{
p.SetValue(this, table.Rows[0][info.Name].ToString(), null);
}
else if (info.PropertyType.Name == "DateTime")
{
p.SetValue(this, (DateTime)table.Rows[0][info.Name], null);
}
else
{
p.SetValue(this, Convert.ToInt32(table.Rows[0][info.Name]), null);
}
}
catch (Exception e)
{
Console.Write(e.ToString());
}
}
}
}
public class Planets : ObjectsInTheSky
{
public Moons[] moons;
}
public class Moons : ObjectsInTheSky
{
}
public class Stars : ObjectsInTheSky
{
public StarTypes type;
public enum StarTypes {Binary,Pulsar,RedGiant}
}
我的问题是,当我尝试使用对象:
Stars star = new Stars(142);
star.type不存在财产的明星,它的存在为star.star。类型,但完全无法访问,或者我无法弄清楚如何访问它。
我不知道我是否正确地扩展了ObjectsInTheSky属性。任何帮助或指针将不胜感激。
您的''''类只有一个无参数的构造函数,由编译器默认提供。 –
仅仅是未来的一点,@ user1224302,Load代码不是必需的(即只是把'/ *东西加载在这里* /'在方法体内) - 人们并不总是懒得向下滚动代码示例(即使我们真的应该)。尽管如此,这是一个该死的网站更好的实际上*拥有*代码比没有 - 所以你已经完成了100%比新用户的50%好) –