本文介绍了添加类型参数约束,以防止抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能限制一个类型参数的抽象类的具体实现,如果这些实现没有默认构造函数?
例如,如果我有
公共抽象类动物 {私人动物() {} 公共动物(字符串名称) { // ... } // ... } 公共类企鹅:动物 { // ... } 酒店的公共类黑猩猩:动物 { // ... }和我也有下面的类:
公共类ZooPen< T> ,其中T:动物 { // ... }我想允许新ZooPen<企鹅>()和新ZooPen<黑猩猩>(),但我想,以禁止新ZooPen<动物方式>()
这是可能的? / p> 解决方案
下面是完成你问的一种方式。
抽象类动物 {只读字符串名称; 动物(){} 公共动物(字符串名称){名称=名称; } } 抽象类动物< T> :动物在那里T:动物< T> {公共动物(字符串名称):基地(名){} } 类企鹅:动物<&企鹅GT; {公共企鹅():基地(企鹅){} } 类黑猩猩:动物<&黑猩猩GT; {公共黑猩猩():基地(黑猩猩){} } 类ZooPen< T>其中T:动物< T> {} 类示例 {无效使用() {变种企鹅=新ZooPen<企鹅> (); 变种黑猩猩=新ZooPen<&黑猩猩GT;(); //此行不会编译 //变种动物=新ZooPen<动物>(); } }
任何人都保持这种代码可能会有点困惑,但它不正是你想要的。
Is it possible to restrict a type parameter to concrete implementations of an abstract class, if those implementations don't have default constructors?
For example, if I have:
public abstract class Animal { private Animal() { } public Animal(string name) { // ... } // ... } public class Penguin : Animal { // ... } public class Chimpanzee : Animal { // ... }And I also have the following class:
public class ZooPen<T> where T : Animal { // ... }I would like to allow new ZooPen<Penguin>() and new ZooPen<Chimpanzee>(), but I would like to disallow new ZooPen<Animal>().
Is this possible?
解决方案Here is one way to accomplish what you're asking for.
abstract class Animal { readonly string Name; Animal() { } public Animal(string name) { Name = name; } } abstract class Animal<T> : Animal where T : Animal<T> { public Animal(string name) : base(name) { } } class Penguin : Animal<Penguin> { public Penguin() : base("Penguin") { } } class Chimpanzee : Animal<Chimpanzee> { public Chimpanzee() : base("Chimpanzee") { } } class ZooPen<T> where T : Animal<T> { } class Example { void Usage() { var penguins = new ZooPen<Penguin>(); var chimps = new ZooPen<Chimpanzee>(); //this line will not compile //var animals = new ZooPen<Animal>(); } }Anyone maintaining this code will probably be a bit confused, but it does exactly what you want.
更多推荐
添加类型参数约束,以防止抽象类
发布评论