0

我正在尝试实现一个相对简单的类层次结构。但是,似乎我的一些知识从学校开始就丢失了。问题是子类的属性在检索时丢失了。

层次结构如下:

  • 具有关于子类的一般属性的抽象类
  • 具有特定属性的子类。从抽象类继承
  • 子类的集合

收藏

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() 以返回过滤器?

4

1 回答 1

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;
}
于 2013-07-18T13:41:07.797 回答