简体   繁体   中英

C# Repository using Generics

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM