好的,所以我有3个不同的类(rl事件的类型) 每个事件都有不同的属性
示例是具有温度,PH值,游泳长度等的游泳类 下一个事件是具有Biketype,轮胎宽度等的Cycling类
现在事件都有一个日期,我想在列表中按日期对它们进行排序。
现在每个类都必须根据设计进行不同的渲染,所以我对如何解决这个问题感到有些困惑?
考虑创建一个对象列表,然后将所有类型的所有事件传递到列表中 按日期排序,, 然后遍历列表并根据我得到的对象类型,将其绑定到usercontrol并呈现它。
这是最好的方法吗?还是有更简单的方法?
答案 0 :(得分:1)
创建所有事件派生自的基类。此基类应具有名为public virtual
的{{1}}方法和Render
字段。
从该类派生所有事件类并覆盖DateTime
方法,以便每个事件类都可以“呈现自己”。
您需要做的就是保留按时间戳排序的基类实例列表,并调用Render
。
样品:
Render
跟踪所有事件的列表:
public class BaseEvent
{
public DateTime TimeStamp;
public virtual void Render() { }
}
public class Swimming : BaseEvent
{
public override void Render()
{
// Code to render a Swimming instance
}
}
public class Cycling: BaseEvent
{
public override void Render()
{
// Code to render a Cycling instance
}
}
渲染所有事件:
private List<BaseEvent> m_events;
答案 1 :(得分:0)
是的,这是一个很好的方法。
但尽量避免自己渲染控件。将它们添加到父容器控件的Controls集合中。 Asp.net将以这种方式呈现控件。
答案 2 :(得分:0)
创建一个其中包含dateTime的类,然后创建其他基于它的类。然后,您可以创建基类列表,并将对象强制转换为扩展类并使用它们。这是一个工作示例
编辑哇我对此感到困惑,不知道如何解释它,所以请求清楚,我会尽我所能
public Form1()
{
InitializeComponent();
List<Sport> Sports = new List<Sport>();
//create a swim object and give it some data
Swimming swim1 = new Swimming();
//create a cycle object and give it some data
Cycling cycle1 = new Cycling();
swim1.PH = 5;
cycle1.BikeType = 2;
// add the two objects to a list of base class
Sports.Add(swim1);
Sports.Add(cycle1);
//iterate through the list of base class and cast the objects to their extended class
//display a independent property of each just to prive it works.
foreach (Sport s in Sports)
{
if (s is Cycling)
{
MessageBox.Show(((Cycling)s).BikeType.ToString());
}
else if (s is Swimming)
{
MessageBox.Show(((Swimming)s).PH.ToString());
}
}
}
}
class Sport
{
DateTime DateAndTime = new DateTime();
}
class Swimming : Sport
{
public int PH = 0;
public int temperature = 0;
}
class Cycling : Sport
{
public int BikeType = 1;
public int TireSize = 26;
}
答案 3 :(得分:0)
几乎和Thorsten Dittmar的解决方案一样,但如果将列表绑定到GridView等控件,则无需关心Render()方法。代替:
1)声明一个新的枚举:
public enum EventType {Swimming, Cycling, etc}
2)像在类声明中一样将枚举值传递给base
public class Cycling: BaseEvent
{
public Cycling() : base(EventValue.Swimming)
}
3)将构造函数添加到BaseEvent,同时添加Event属性
public class BaseEvent
{
public BaseEvent(EventType type)
{
Event = type;
}
EventType Event { get; set; }
DateTime EventDate ....
}
4)然后将类型List<BaseEvent>
的列表绑定到您的控件,并在OnItemDataBound事件中根据Event属性值将您想要的任何内容绑定到