Skip to main content
 首页 » 编程设计

C# 通用部分类、接口(interface)和继承,都在同一个问题中! (天啊!)

2024年02月24日13jirigala

我一直在为我的项目开发代码生成器,而且一切都运行良好。但是现在,我偶然发现了一个我不确定如何解决的细节。这是我的 DAL 层,旨在允许实现不同的数据源。

所以我有一个接口(interface):

public interface IUsersDALBase 
{ 
    //defined methods 
} 

实现它的通用类:

public class UsersDALBase<T> : DBDataAccessBase where T : DBDataAccessBase, IUsersDALBase, new() 
{    
    protected T _UsersInstance = default(T); 
 
    public string connectionString 
    { 
        get { return _UsersInstance.connectionString; } 
        set { _UsersInstance.connectionString = value; } 
    } 
 
    //constructors (...) 
 
    //interface method implementations, that call _UsersInstance methods    (...) 
} 

作为引用,DBDataAccessBase 仅保存连接字符串,并具有标准化*DALBAse 类的配置方法。还有一个空的派生定义来扩展(并且不需要“Base”后缀):

 public partial class UsersDAL<T> : UsersDALBase<T>  where T : DBDataAccessBase, IUsersDALBase, new() 
{ 
    //empty in generated file 
} 

此类只是 UsersDALBase 的包装器,也是我想在新文件中扩展的类。 T 类型类也主要是自动生成的,但具有特定于 DB 的实现。

最后,我想在另一个文件中扩展 UsersDAL,使用生成的代码没有的自定义方法,并用新接口(interface)表示

public interface IUsers2 
{ 
   UsersList GetAppRoleUsers(int NS_AppRole); 
} 

我正在尝试类似的东西:

public partial class UsersDAL<T> : UsersDALBase<T> where T : DBDataAccessBase, IUsers2, new() 
{ 
    //interface method implementation 
 
    //compile error: Partial declarations of 'DAL.UsersDAL<T>' have inconsistent  
    //constraints for type parameter 'T' -supose i can't have diferente interface  
    //implementations for T...   
 
} 

我基本上希望 UserDAL 拥有所有自动生成的方法(实现 IUsersDALBAse)和我在新接口(interface) IUsers2 中定义的方法。关于如何获得这个的任何想法???

谢谢!

请您参考如下方法:

如果多个文件指定了类型约束,恐怕这些约束必须匹配。

来自 C# 3 规范的第 10.2.3 节:

When a partial generic type declaration includes constraints (where clauses), the constraints must agree with all other parts that include constraints. Specifically, each part that includes constraints must have constraints for the same set of type parameters, and for each type parameter the sets of primary, secondary, and constructor constraints must be equivalent. Two sets of constraints are equivalent if they contain the same members. If no part of a partial generic type specifies type parameter constraints, the type parameters are considered unconstrained.

您能否在部分类声明中提供您想要的任何额外接口(interface)作为代码生成器的输入?