我可以简化我的课程以使他们更干吗?

时间:2012-09-12 14:18:49

标签: c#

我有以下ViewModel类:

public class ReferenceDetailsViewModel
{
    public ReferenceDetailsViewModel() {
        this.Timer = new List<long>();
    }
    public IEnumerable<Reference.Grid> Grid { get; set; }
    public List<long> Timer { get; set; }
}

public class ContentDetailsViewModel
{
    public ContentDetailsViewModel() {
        this.Timer = new List<long>();
    }
    public IEnumerable<Content.Grid> Detail { get; set; }
    public SelectList Statuses { get; set; }
    public SelectList Types { get; set; }
    public List<long> Timer { get; set; }
}

它们都有一个共同的Timer字段,这在构造函数中初始化。

有没有办法可以创建一个baseViewModel并让它们继承Timer字段,以避免为每个有定时器的ViewModel编码相同的东西?

3 个答案:

答案 0 :(得分:2)

是的,编写一个抽象类,并使具体类继承自此。

public abstract class BaseDetailsViewModel
{
    protected BaseDetailsViewModel() {
        Timer = new List<long>();
    }
    public List<long> Timer { get; set; }
}

答案 1 :(得分:1)

如果我理解正确,您可以执行以下操作:

public abstract class DetailViewModelBase
{
    protected DetailViewModelBase()
    {
        Timer = new List<long>();
    }

    public List<long> Timer { get; set; }
}

public class ReferenceDetailsViewModel : DetailViewModelBase
{
    public IEnumerable<Reference.Grid> Grid { get; set; }
}


public class ContentDetailViewModel : DetailViewModelBase
{
    public IEnumerable<Content.Grid> Detail { get; set; }
    public SelectList Statuses { get; set; }
    public SelectList Types { get; set; }

}

使用'DetailViewModelBase'作为包含'Timer'的ViewModels的基类。

问候,C#er

答案 2 :(得分:1)

如果您可以从IGridReference.Grid中提取常用Content.Grid界面,则可能会获得

public abstract class GridViewModel<TGrid> where T : IGrid {
    protected GridViewModel() {
        Timer = new List<long>();
    }

    public List<long> Timer { get; set; }
    public IEnumerable<TGrid> Details { get; set; }
}

public class ReferenceDetailsViewModel : GridViewModel<Reference.Grid> { 

}

public class ContentDetailsViewModel : GridViewModel<Content.Grid> {
    public SelectList Statuses { get; set; }
    public SelectList Types { get; set; }
    public List<long> Timer { get; set; }
}

我认为您可以将ReferenceDetailsViewModel.Grid重命名为ReferenceDetailsViewModel.Details