// T => a class
// I => Guid, int etc..
public interface IBaseX<T, I>
where T : BaseY<I> {..}
public class BaseX<T, I> : IBaseX<T, I>
where T : BaseY<I> {..}
// it works but,
public interface IMyClass<T, I>
where T : IBaseX<T, I> {..}
public class MyClass<T, I>
where T : BaseX<T, I>, IMyClass<T, I>
// this not works, why not?
錯誤: 類型T不能被用作在通用類型或方法IBaseX類型參數T。有沒有裝箱轉換或類型參數轉換從T到BaseY我如何在接口<T, I>創建兩種類型的繼承兩種類型的接口<T, I>
有一些問題,我寫更新:
我有一個ORM的項目,包括:
在項目的根目錄: BaseEntity.cs:
public abstract class BaseEntity<T>
{
public T ID { get; set; }
.....
}
內容文件夾: Page.cs:
個public class Page : BaseEntity<int>
{
[MaxLength(250)]
[Required]
public string Title { get; set; }
....
}
PageComment.cs:
public class PageComment : BaseEntity<int>
{
public int PageID { get; set; }
[Required]
[MaxLength(500)]
public string Body { get; set; }
[Required]
[MaxLength(175)]
public string Email { get; set; }
[Required]
[MaxLength(150)]
public string Title { get; set; }
....
}
我有一個數據層的項目,包括:
基本文件夾:
IBaseDAL.cs:
public interface IBaseDAL<T, I> where T : BaseEntity<I>
{
void Save(T e, string who, WebsiteContext ctx = null);
void Update(T e, string who, WebsiteContext ctx = null);
void Delete(T e, string who, WebsiteContext ctx = null);
}
BaseDAL.cs :
public class BaseDAL<T, I> : IBaseDAL<T, I> where T : BaseEntity<I>
{
public void Save(T e, string who, WebsiteContext ctx = null) { ... }
}
評論文件夾:
ICommentDAL.cs:
public interface ICommentDAL<T> where T : BaseEntity<int>, IBaseDAL<T, int>
{
int Save(WebsiteContext ctx, NewCommentDTO nc, string who);
....
}
CommentDAL.cs:
public class CommentDAL<T>
where T : BaseEntity<int>, IBaseDAL<T, int>, ICommentDAL<T>
{
BaseDAL<T, int> baseDAL = new BaseDAL<T, int>();
public int Save(WebsiteContext ctx, NewCommentDTO<T> nc, string who)
{
ORM.Content.PageComment pc = new PageComment()
{
Body = nc.Body,
...
};
baseDAL.Save(pc as T, who, ctx);
}
}
ORM.Content.PageComment類必須爲T
但使用,如果我寫「T.」,來到BaseEntity字段..
在serviceLayer中,我將調用commentDAL.Save方法:
_commentDAL.Save(...);
我如何可以傳遞commentDAL.Save值T級()
所以,你要'''T:BaseX {..}'''或'''T:BaseY {..}'''? –
tym32167
基數x中的T需要是基數Y –
通用類型約束沒有「繼承」 - 您必須明確包含您的基類型或接口所需的任何約束。 –