Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 与泛型纠缠不清_C#_Generics - Fatal编程技术网

C# 与泛型纠缠不清

C# 与泛型纠缠不清,c#,generics,C#,Generics,我有以下域对象: public class DomainObject<T,TRepo> where T : DomainObject<T> where TRepo : IRepository<T> { public static TRepo Repository { get;private set; } } 公共类域对象 其中T:DomainObject TRepo在哪里:我相信 { 公共静态TRepo存储库{get;private s

我有以下域对象:

public class DomainObject<T,TRepo> 
  where T : DomainObject<T>
  where TRepo : IRepository<T>
{
      public static TRepo Repository { get;private set; }
}
公共类域对象
其中T:DomainObject
TRepo在哪里:我相信
{
公共静态TRepo存储库{get;private set;}
}
存储库界面:
public interface IRepository//其中T:DomainObject//catch 22
{
无效保存(T域对象);
}
第2条的实施:
公共类用户:DomainObject
{
公共字符串名称{get;private set;}
}
公共类MyRepository:IRepository
{
公共列表用户SwithNameBob()
{
}
}
因此,添加另一个不在IRepository中的方法

我希望将存储库强制为IRepository,而在上面,它可以是任何类型

一个小的旁注:我写这篇文章是为了有很少域对象的小系统。我不想创造任何使用IoC的东西,而是想创造一些简单易用的东西


感谢您,DomainObject的实现只指定了一个泛型类型参数,而不是两个。为什么不是:

public class User : DomainObject<User, MyRepository>
{
    public string Name { get;private set;}
}
公共类用户:DomainObject
{
公共字符串名称{get;private set;}
}

如果这不起作用,你能解释一下它以什么方式不能满足你的需要吗?

不完全确定你想要什么,但类似的编译:

public class DomainObject<T, TRepo> 
     where T: DomainObject<T, TRepo> 
     where TRepo: IRepository<T, TRepo>
{
     public static TRepo Repository
     {
         get;
         private set; 
     }
}

public interface IRepository<T, TRepo>
     where T: DomainObject<T, TRepo>
     where TRepo: IRepository<T, TRepo>
{
     void Save(T domainObject);
}
公共类域对象
其中T:DomainObject
TRepo在哪里:我相信
{
公共静态TRepo存储库
{
得到;
私人设置;
}
}
公共接口假定
其中T:DomainObject
TRepo在哪里:我相信
{
无效保存(T域对象);
}

这是一个疏忽,现在修复了第二点,我想避免为了访问它在iRepository上提供的添加而强制转换到我的自定义存储库。我刚刚测试了它,它似乎一切正常<代码>DomainUser.Repository.UsersWithNameBob()解决了A-OK。您不需要强制转换:
用户。存储库
的类型将是
MyRepository
。同意,我根本看不到问题。这就是我想要的:)告诉界面它是一个IRepository感觉有点不自然,因为它正在实现它。好吧,您已经对域对象做了同样的事情;)您是否测试过您实际上必须强制转换User.Repository?因为您不必这样做,它将是MyRepository类型的,因此无需更改代码即可访问UsersWithNameBob。
public class User : DomainObject<User, MyRepository>
{
    public string Name { get;private set;}
}
public class DomainObject<T, TRepo> 
     where T: DomainObject<T, TRepo> 
     where TRepo: IRepository<T, TRepo>
{
     public static TRepo Repository
     {
         get;
         private set; 
     }
}

public interface IRepository<T, TRepo>
     where T: DomainObject<T, TRepo>
     where TRepo: IRepository<T, TRepo>
{
     void Save(T domainObject);
}