开发者

Creating Stub for C# Generic Type Method

I have a generic method: (simplified)

public class DataAccess : IDataAccess
{
    public List<T> GetEntity<T>()
    {
       return GetFromDatabase<T>(); //Retrieve from database base on Type parameter
   开发者_JAVA技巧 }
}

For testing purpose, I want to create a stub from which I want 'Foo' should be returned with some data:

public class DataAccessStub : IDataAccess
{
    public List<T> GetEntity<T>()
    {
       List<Foo> listFoo = new List<Foo>();
       Foo foo = new Foo();
       foo.Name = "Some Name";
       listFoo.Add(foo);

       return listFoo; // I want Foo to be returned
    }
}

Since T has not identified what type it is yet, I can't return List<Foo>. Compiler error will occur. So How can I write a stub for this kind of generic method?

Edit: Changed the code a little bit. The first method will retrieve from the database base on Type Parameter. The second is a stub for testing. Sorry that I am not sure if this explain what I want to mention.

Thanks.


    interface IA
{
    List<T> Get<T>();
}

class StubA : IA
{
    public List<T> Get<T>()
    {
        var item = new Foo();
        var data = new List<Foo> {item};
        return new List<T>(data.Cast<T>());
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜