【发布时间】:2014-02-16 12:56:30
【问题描述】:
public abstract class Shape
{
public String toString()
{
// ...
return "";
}
}
public class Rectangle : Shape
{
public Double width { get; set; }
public Double height { get; set; }
}
假设我从 Rectangle 类创建了一个对象。有没有办法通过创建的对象编写具有值的 Rectangle 类对象的属性而不覆盖 toString() 方法?
编辑:
实际上我的目的是为所有子类创建一个通用的 ToString() 方法。
我修改了我的代码
public abstract class Shape
{
public virtual String ToString(Shape shape)
{
String result = String.Empty;
foreach (var property in shape.GetType().GetProperties())
{
result += property.Name + " : " + property.GetValue(shape, null) + "\n";
}
return result;
}
}
public class Rectangle : Shape, IRectangle
{
public Double width { get; set; }
public Double height { get; set; }
public override String ToString()
{
return base.ToString(this);
}
}
结果:
width : 0
height : 0
但是现在,我必须为所有子类重写 ToString() 方法。我找不到此代码重复的解决方案
【问题讨论】:
-
“写 Recatangle 类对象的属性...”我不确定我是否遵循。
-
不,不可能,因为基类对派生类一无所知。
-
坦率地说,以其他方式来做更多的工作。
-
执行此操作并将所有代码保留在基础中的唯一其他方法是在运行时反映 .ToString() 中的属性,但这似乎不是一个好主意。
-
我现在看到你也标记了这个问题
reflection。你的实际问题是"How to get the list of properties of a class?"?
标签: c# oop reflection