开发者

Creating a base class based in List<T>

I have a need to create a couple of classes that will serve as base classes for some data functionality I want to implement.

The first, we'll call SessionObjectDataItem looks like this ...

public class ObjectSessionDataItem
{
  public int ID { get; set; }

  public bool IsDirty { get; set; }

  public bool IsNew { get; set; }

  public bool IsRemoved { get; set; }
}

And next I want a List called ObjectSessionDataList and this is where I get stuck.

I can create the class OK ...

public class SessionObjectDataList<SessionObjectDataItem> : List<SessionObjectDataItem>
{

}

where I fall down is trying to define properties on the list that access items in it. For example, I want to write...

public List<SessionObjectDataItem> DirtyItems
{
    get
    {
        return this.Where(d => d.IsDirty).ToList();
    }
}

but VS refuses to recognise the SessionObjectDataItem property IsDirty inside the List object definition.

What I'm trying to end up with is a case where I might define

public class AssociatedDocument : SessionObjectDataItem
{
    ...
}

public class DocumentList : SessionObjectDataList
{

}

And then be able to say...

DocumentList list = new DocumentList();
...
foreach(AssociatedDocument doc in list.DirtyItems)
{
    ...
}

Can I actually do what it is开发者_如何学JAVA that I'm attempting? Am I just doing it wrong?


Generic constraints will help here; you can write a container-class for which the generic type-parameter is constrained to be SessionObjectDataItem or one of its subtypes. This will allow you to construct a generic class that can hold instances of a specific sub-type of SessionObjectDataItem.

public class SessionObjectDataList<T> : List<T> where T : SessionObjectDataItem
{
    public SessionObjectDataList<T> DirtyItems
    {
       get
       {
           return this.Where(d => d.IsDirty).ToList();
       }
    }
}

Usage:

var list = new SessionObjectDataList<AssociatedDocument>();
...

foreach(AssociatedDocument doc in list.DirtyItems)
{
    ...
}


Try to use the generic version Where<T> of the queryable interface:

public List<SessionObjectDataItem> DirtyItems
{
    get
    {
        return this.AsQueryAble().Where<SessionObjectDataItem>(d => d.IsDirty).ToList();
    }
}

Else Where simply assumes d as type Object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜