添加类型参数约束,以防止抽象类

编程入门 行业动态 更新时间:2024-10-28 14:22:33
本文介绍了添加类型参数约束,以防止抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有可能限制一个类型参数的抽象类的具体实现,如果这些实现没有默认构造函数?

例如,如果我有

公共抽象类动物 {私人动物() {} 公共动物(字符串名称) { // ... } // ... } 公共类企鹅:动物 { // ... } 酒店的公共类黑猩猩:动物 { // ... }

和我也有下面的类:

公共类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.

更多推荐

添加类型参数约束,以防止抽象类

本文发布于:2023-10-26 21:37:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531418.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   类型   抽象类   以防止

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!