C# &引用;其中;c语言中类声明中的关键字
有谁能帮我在下面的类声明中添加一行C# &引用;其中;c语言中类声明中的关键字,c#,.net,generics,C#,.net,Generics,有谁能帮我在下面的类声明中添加一行where tenty:class,ienty,new() public abstract class BaseEntityManager<TEntity> where TEntity : class, IEntity, new() 公共抽象类BaseEntityManager 其中tenty:class、ienty、new() 其中tenty:…将约束应用于通用参数tenty。在这种情况下,约束条件是: 类:TEntity的参数必
where tenty:class,ienty,new()
public abstract class BaseEntityManager<TEntity>
where TEntity : class, IEntity, new()
公共抽象类BaseEntityManager
其中tenty:class、ienty、new()
其中tenty:…
将约束应用于通用参数tenty。在这种情况下,约束条件是:
类:TEntity的参数必须是引用类型IEntity:参数必须是或实现IEntity接口
new():参数必须具有公共无参数构造函数
其中是泛型类型约束。这些行表示类型TEntity必须是引用类型而不是值类型,必须实现接口TEntity,并且必须具有不接受参数的构造函数
类声明后的
where
关键字限制了泛型tenty
可以是什么类型。在这种情况下,tenty
必须是一个类(这意味着它不能是像int
或DateTime
这样的值类型),并且它必须实现接口ienty
。new()
约束表示该类中的方法能够调用由tenty
表示的泛型类的默认构造函数(例如newtenty()
)问题是什么
让我来看看我认为问题是什么。该约束确保您只能使用泛型参数对BaseEntityManager进行子类化,泛型参数是一种实现IEntity并包含无参数构造函数的引用类型
E.X
公共类产品:智能{
公共产品(){}
}
公共类错误{
公共错误(){}
}
公众阶级的错误又来了:理性{
私有错误(){}
}
//汇编
公共产品管理器:BaseEntityManager{}
//错误-未实现有效性
公共管理器:BaseEntityManager{}
/错误-没有公共无参数构造函数
公共错误管理器:BaseEntityManager{}
请看我想他是在要求解释语法。“有人能帮我写这句话吗…?”这就是问题所在。很明显,他在问什么。如果你能添加一些代码,展示某人如何使用BaseEntityManager作为基类,那将是非常棒的:)
public class Product : IEntity {
public Product() {}
}
public class Wrong {
public Wrong() {}
}
public class WrongAgain : IEntity {
private Wrong() {}
}
// compiles
public ProductManager : BaseEntityManager<Product> {}
// Error - not implementing IEntity
public WrongManager : BaseEntityManager<Wrong> {}
/ Error - no public parameterless constructor
public WrongAgainManager : BaseEntityManager<WrongAgain> {}