2013-01-21 181 views
3

我想在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属性。任何帮助或指针将不胜感激。

+1

您的''''类只有一个无参数的构造函数,由编译器默认提供。 –

+0

仅仅是未来的一点,@ user1224302,Load代码不是必需的(即只是把'/ *东西加载在这里* /'在方法体内) - 人们并不总是懒得向下滚动代码示例(即使我们真的应该)。尽管如此,这是一个该死的网站更好的实际上*拥有*代码比没有 - 所以你已经完成了100%比新用户的50%好) –

回答

6

看起来好像您正尝试使用未在子类Stars或基类中定义的构造函数。

Stars star = new Stars(142); 

如果您尝试使用.Load(int)方法,那么你需要做的是:

Stars star = new Stars(); 
star.Load(142); 

或者,如果你想使用基本的构造函数,你需要在定义它子类:

public class Stars : ObjectsInTheSky 
{ 
    public Stars(int id) : base(id) // base class's constructor passing in the id value 
    { 
    } 

    public Stars() // in order to not break the code above 
    { 
    } 

    public StarTypes type; 
    public enum StarTypes {Binary,Pulsar,RedGiant} 
} 
+0

他可能只是想添加额外的构造函数到所有子类型,因为'Load'可能不应该公开。 – Servy

+0

...或者在'Stars'中添加一个'int'构造函数,这个构造函数的通道在ObjectsInTheSky中相同 –

+0

谢谢,我还添加了子类型构造函数的创建。 –

2

C#中的构造函数没有被继承。你需要额外的构造函数重载添加到每个基类:

public class Stars : ObjectsInTheSky 
{ 
    public Stars(int id) : base(id) { } 

    public StarTypes type; 
    public enum StarTypes {Binary,Pulsar,RedGiant} 
} 

这将创建一个构造函数,只是调用基类的构造函数为您服务。