简体   繁体   中英

C#: Can I code public class MyGenericClass<T> where T:MyClass AND implement an Interface?

I see this:

public class MyGenericClass<T> where T:IComparable { }

and I have this:

public class ProductRepository : IRepository<Product> { }

How would you code something like this?

public class ProductRepository<T> where T : Product : IRepository<Product> {}

After all that, I thought I could simply make a single Repository class then inject the type to it, including the data context. But, we pursue the simplest thing first right? LOL

Update:

If I did this, how would I choose which Entity to use in the Entity Container (or Context)? (Third line from the bottom starting with return _dc.Versions., which would somehow need switched to return _dc.T. )

public class Repository<T> : IRepository<T> where T : class
{   
    # region Constructor
    private AdSketchEntities _dc { get; set; } // Data Container (Data Context)
    public Repository() : this(new AdSketchEntities()) { }
    public Repository(AdSketchEntities myDC)
    {   this._dc = myDC; 
    }
    # endregion

    public T Add(T entity)
    {
        _dc.Versions.AddObject(entity);
        return _dc.Versions.Where(n => n.custid == entity.custid &&
                       n.versionid == entity.versionid).SingleOrDefault();
    }

You can specify multiple constraints like this:

public class ProductRepository<T>
    where T : Product, IRepository<Product>
{
}

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