开发者

c# How to implement a collection of generics

I have a worker class that does stuff with a collection of objects. I need each of those objects to have two properties, one has an unknown type and one has to be a number.

I wanted to use an interface so that I could have multiple item classes that allowed for other properties but were forced to have the PropA and PropB that the worker class requires.

This is the code I have so far, which seemed to be OK until I tried to use it. A list of MyItem is not allowed to be passed as a list of IItem even though MyItem implements IItem. This is where I got confused.

Also, if possible, it would be great if when instantiating the worker class I don't need to pass in the T, instead it would know what T is based on the type of PropA.

Can someone help get me sorted out? Thanks!

public interface IItem<T>
{
    T 开发者_开发知识库PropA { get; set; }
    decimal PropB { get; set; }
}

public class MyItem : IItem<string>
{
    public string PropA { get; set; }
    public decimal PropB { get; set; }
}

public class WorkerClass<T>
{
    private List<T> _list;

    public WorkerClass(IEnumerable<IItem<T>> items)
    {
        doStuff(items);
    }
    public T ReturnAnItem()
    {
        return _list[0];
    }
    private void doStuff(IEnumerable<IItem<T>> items)
    {
        foreach (IItem<T> item in items)
        {
            _list.Add(item.PropA);
        }
    }
}
public void usage()
{
    IEnumerable<MyItem> list= GetItems();
    var worker = new WorkerClass<string>(list);//Not Allowed
}


You can make this work if you supply the interface directly instead of the concrete type. It just isn't able to do the implicit conversion for you:

IEnumerable<IItem<string>> items = GetItems().Cast<IItem<string>>();
var worker = new WorkerClass<string>(items);

On an aside: Your original code would actually work in C# 4, which supports covariance on IEnumerable<T>. But previous versions of C# don't, which is why you get the error.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜