加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#界面限制

发布时间:2020-12-15 07:59:33 所属栏目:百科 来源:网络整理
导读:我正在尝试通用约束.在声明类的约束时如此: public class DocumentPrinterT where T : IFooDoc 我能够在DocumentPrinter类的方法中访问IFooDoc声明的方法.但是,如果我使DocumentPrinter实现一个声明约束的接口,例如: public interface IDocumentPrinterT w
我正在尝试通用约束.在声明类的约束时如此:
public class DocumentPrinter<T> where T : IFooDoc

我能够在DocumentPrinter类的方法中访问IFooDoc声明的方法.但是,如果我使DocumentPrinter实现一个声明约束的接口,例如:

public interface IDocumentPrinter<T> where T : IFooDoc
{
    void Add(T fooDoc);
    void PrintFoos();
}

然后将DocumentPrinter声明为:

public class DocumentPrinter<T>: IDocumentPrinter<T>

IFooDoc实例的属性/方法在Document打印机的方法中不再可用.似乎我必须在类本身声明一个接口约束,如果我要访问该类型声明的成员.

我是否正确理解这一点,或者是否可以在接口上声明约束并让类实现该约束?

解决方法

Do I understand this correctly or is it possible to declare the constraint on the interface and to have that constraint realized by the class?

正确.你有1来声明泛型类的类型参数的约束.仅仅因为你在DocumentPrinter中命名了type参数< T>与IDocumentPrinter< T>中的type参数同名并不意味着它们是相同的类型.当你申报时

public class DocumentPrinter<T> : IDocumentPrinter<T>

你实际上是在说使用T参数化DocumentPrinter< T>参数化IDocumentPrinter< T>现在它们是相同的类型.但为了合法,来自DocumentPrinter的T< T>必须满足IDocumentPrinter< T>的类型参数的所有约束.因此,您必须明确地说T满足T:IFooDoc.

1:显然我需要明确说明.如果您不执行语言规范要求您执行的操作,则您的代码将无法编译.语言规范要求在参数化泛型类型时,使用它参数化的类型必须满足该泛型类型的该类型参数的所有约束.如果不这样做,您的代码将无法编译.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读