【发布时间】:2013-01-04 19:41:06
【问题描述】:
我正在尝试在 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.star.type 存在但完全无法访问,或者我不知道如何访问它。
我不知道我是否正确扩展了 ObjectsInTheSky 属性。任何帮助或指示将不胜感激。
【问题讨论】:
-
你的
Stars类只有一个无参数的构造函数,编译器默认提供。 -
只是未来的一点,@user1224302,
Load的代码不是必需的(即只需在方法的主体中添加类似/* stuff loaded here */的内容)- 人们不需要总是费心向下滚动代码示例(即使我们确实应该这样做)。尽管如此,实际上拥有代码总比没有代码要好 - 所以你已经比 50% 的新用户做得好 100% ;)
标签: c# inheritance base-class