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

时间:2009-07-22 15:00:04

标签: c# generics inheritance interface

我一直在为我的项目开发代码生成器,虽然一切都运行良好。但现在,我偶然发现了一个我不确定如何解决的细节。这适用于我的DAL层,旨在允许实现diferente dataSources。

所以我有一个界面:

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,并用新接口表示

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)以及我在新接口IUsers2中定义的方法。我怎么能得到这个???

谢谢!

1 个答案:

答案 0 :(得分:4)

如果多个文件指定了类型约束,那么我担心这些约束必须匹配。

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

  

当部分泛型类型时   声明包括约束   (where子句),约束必须   同意所有其他部分   包括约束。特别,   每个包含约束的部分   必须对同一组具有约束   类型参数,以及每种类型   参数集主要,   辅助和构造函数约束   必须是等同的。两套   约束是相等的,如果它们   包含相同的成员。如果没有部分   部分泛型类型的指定   类型参数约束,类型   参数被考虑   不受约束。

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