C# 如何为泛型类的类型参数设置int默认值并支持自定义传入
实现方案
C# 泛型类本身不支持直接为类型参数设置默认值,但可以通过声明两个重载版本的BaseEntity类实现你期望的使用效果,无需每次显式传递int类型参数:
第一步:定义通用泛型版本
先实现带泛型参数的BaseEntity,将类型透传给父类Identifiable:
public class BaseEntity<T> : Identifiable<T> { // 原有BaseEntity的全部逻辑,比如自动填充字段的实现 public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } }
第二步:定义默认类型的非泛型版本
额外声明一个无泛型参数的BaseEntity,继承自int类型的泛型版本,作为默认实现:
public class BaseEntity : BaseEntity<int> { // 无需重复实现逻辑,仅需要透传构造函数即可(如果父类有自定义构造的话) // 示例:如果泛型BaseEntity有带参构造,加一行即可 // public BaseEntity(xxx参数) : base(xxx参数) {} }
最终使用效果
完全符合你期望的写法:
- 自定义ID类型时,传入对应泛型参数即可:
class AnotherEntity : BaseEntity<Guid> { // 此处ID类型为Guid }
- 不需要自定义类型时,直接继承默认BaseEntity:
class AnotherEntityAgain : BaseEntity { // 此处ID类型为默认int }
内容的提问来源于stack exchange,提问作者LEBBER
相关产品推荐
相关产品推荐

