简体   繁体   English

C#:我可以编写公共类MyGenericClass吗 <T> 在哪里T:MyClass并实现一个接口?

[英]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. 毕竟,我认为我可以简单地创建一个Repository类,然后将类型(包括数据上下文)注入其中。 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. ) (从底部开始的第三行以return _dc.Versions。开头,这将以某种方式需要切换以返回_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>
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# 不强制 class 实现公共接口 - C# not forcing class to implement public interface 铸造MyClass <T> 到MyClass <object> C# - Casting MyClass<T> to MyClass<object> C# C# public class where T : class, Class, new() 混淆 - C# public class where T : class, Class, new() confusion C#在“其中TEntity:类”上实现接口 - C# implement interface on “where TEntity : class” 公共 T GetMyClass<t> () where T: MyClass, new() { /* 这没有意义吗? */ }</t> - public T GetMyClass<T>() where T : MyClass, new() { /* is this pointless? */ } C#泛型:我可以约束一组没有实现接口的类吗? - C# Generics: Can I constrain to a set of classes that don't implement an interface? C# 接口和类。 接口中需要的类中使用的变量不能是私有的,或者私有的只能是公共的。 为什么? - C# Interfaces and classes. Variables used in the class needed in the interface can't be private, or private only public. Why? c#接口方法<T>但实现为concreate - c# interface with method<T> but implement as concreate 谁能解释一下层次树公共接口IGenericRepository<t> 其中T:class?</t> - can any one explain the hierarchy tree public interface IGenericRepository<T> where T: class? 重命名 c# 类,现在我无法访问该类中的公共常量变量 - Renamed c# class and now I can't access the public const variables in that class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM