我正在尝试实现一个相对简单的类层次结构。但是,从学校开始,我的一些知识似乎就丢失了。问题是子类的属性在检索时会丢失。
层次结构如下:
集合
public class ActiveFilters
{
public List<ActiveFilter> Filters { get; set; }
enum FilterTypes
{
DateRange = 1,
CheckBox = 2,
TextBox = 3,
RadioButtons = 4
};
public ActiveFilters()
{
Filters = new List<ActiveFilter>();
//Required filters on start
Filters.Add(
new FilterDateRange(
"/statistikstart.aspx",
(int)FilterTypes.DateRange,
"paymentDate",
new DateTime(1800, 1, 1),
DateTime.Now.AddDays(7)
)
);
Filters.Add(
new FilterDateRange(
"/statistikgiro.aspx",
(int)FilterTypes.DateRange,
"paymentDate",
new DateTime(1800, 1, 1),
DateTime.Now
)
);
}
public ActiveFilter GetActiveFilter(string source, string name)
{
try
{
return Filters.FirstOrDefault(x => x.Source == source && x.Name == name) as ActiveFilter;
}
catch
{
//Filter not in collection
return null;
}
}
}
抽象类
public abstract class ActiveFilter
{
public string Source { get; set; }
public int Type { get; set; }
public string Name { get; set; }
}
子类
public class FilterDateRange : ActiveFilter
{
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public FilterDateRange(string source, int type, string name, DateTime fromDate, DateTime toDate)
{
base.Source = source;
base.Type = type;
base.Name = name;
this.FromDate = FromDate;
this.ToDate = ToDate;
}
}
当我尝试从集合构造函数中检索一个创建的过滤器时,子类中没有保存日期。保存的唯一信息是抽象类的属性:
FilterDateRange test = ((FilterDateRange)((ActiveFilters)Session["activeFilters"]).GetActiveFilter("/statistikstart.aspx", "paymentDate"));
问题是我从GetActiveFilter()而不是子类返回ActiveFilter吗?如果是这样,当过滤器可以是不同的子类时,如何重写GetActiveFilter()以返回过滤器?
答案 0 :(得分:3)
你有一些拼写错误:
public FilterDateRange(string source, int type, string name, DateTime fromDate, DateTime toDate)
{
base.Source = source;
base.Type = type;
base.Name = name;
this.FromDate = FromDate; // set FromDate to FromDate (the property)
this.ToDate = ToDate;
}
应该是
public FilterDateRange(string source, int type, string name, DateTime fromDate, DateTime toDate)
{
base.Source = source;
base.Type = type;
base.Name = name;
this.FromDate = fromDate; // set FromDate to fromDate (the parameter)
this.ToDate = toDate;
}