[英]C# Object Inheritance
I am trying to create a base class in c# that I can extend out to sub classes. 我试图在c#中创建一个基类,我可以扩展到子类。
For example: 例如:
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}
}
My problem is when I try to use an object: 我的问题是当我尝试使用一个对象时:
Stars star = new Stars(142);
star.type does not exists and property of star, it exists as star.star.type but completely inaccessable, or I can not figure out how to access it. star.type不存在和star的属性,它以star.star.type存在但完全无法访问,或者我无法弄清楚如何访问它。
I do not know if I'm extending the ObjectsInTheSky property properly or not. 我不知道我是否正确扩展了ObjectsInTheSky属性。 Any help or pointers will be greatly appreciated. 任何帮助或指示将不胜感激。
It looks as though you are trying to use a constructor that is not defined on your subclass Stars
or the base class. 看起来好像您正在尝试使用未在子类Stars
或基类上定义的构造函数。
Stars star = new Stars(142);
If you are trying to use the .Load(int)
method then you would need to do this: 如果您尝试使用.Load(int)
方法,则需要执行以下操作:
Stars star = new Stars();
star.Load(142);
Or, if you are trying to use the base constructor, you need to define it in the subclass: 或者,如果您尝试使用基础构造函数,则需要在子类中定义它:
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}
}
Constructors in C# are not inherited. C#中的构造函数不是继承的。 You need to add the additional constructor overloads to each of the base classes: 您需要为每个基类添加额外的构造函数重载:
public class Stars : ObjectsInTheSky
{
public Stars(int id) : base(id) { }
public StarTypes type;
public enum StarTypes {Binary,Pulsar,RedGiant}
}
This will create a constructor that just calls the base class's constructor for you. 这将创建一个构造函数,只为您调用基类的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.