开发者

C# Repository using Generics

开发者 https://www.devze.com 2023-01-20 11:38 出处:网络
I have the following repository that I use for unit testing: public class MyTestRepository<T> { private List<T> entities = new List<T>();

I have the following repository that I use for unit testing:

public class MyTestRepository<T>
{
    private List<T> entities = new List<T>();

    public IQueryable<T> Entities
    {
        get { return entities.AsQueryable(); }
    }

 开发者_运维技巧   public T New()
    {
        //return what here???
    }

    public void Create(T entity)
    {
        entities.Add(entity);
    }

    public void Delete(T entity)
    {
        entities.Remove(entity);
    }
}

What do I return in the New() method?

I have tried this:

    public T New()
    {
        return (T) new Object();
    }

But that gives me the following exception when I run my unit test:

System.InvalidCastException: Unable to cast object of type 'System.Object' to type 'MyCustomDomainType'.

Any idea on how to implement the New() method?


You could add a constraint for the T type parameter:

public class MyTestRepository<T> where T : new() 

and return new T(); in the method.


You should change your repository definition by adding the new() constraint, like this:

public class MyTestRepository<T> where T : new()
{
    ...
}

This constrains types that can be used with MyTestRepository to those that have a default constructor. Now, in your New() method you can do:

public T New()
{
    return new T();
}


Assuming type T has a public / default constructor, would this not correct the exception?

public T New()
{
    return new T();
}


That won't work as you're just creating an object, nothing else. How about creating the object with Activator:

return (T)Activator.CreateInstance(typeof(T));

See: http://msdn.microsoft.com/en-us/library/system.activator.aspx

0

精彩评论

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