[英]C# Object Inheritance
我試圖在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
或基類上定義的構造函數。
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}
}
C#中的構造函數不是繼承的。 您需要為每個基類添加額外的構造函數重載:
public class Stars : ObjectsInTheSky
{
public Stars(int id) : base(id) { }
public StarTypes type;
public enum StarTypes {Binary,Pulsar,RedGiant}
}
這將創建一個構造函數,只為您調用基類的構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.