微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#界面限制

我正在尝试通用约束.在声明类的约束时如此:
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:显然我需要明确说明.如果您不执行语言规范要求您执行的操作,则您的代码将无法编译.语言规范要求在参数化泛型类型时,使用它参数化的类型必须满足该泛型类型的该类型参数的所有约束.如果不这样做,您的代码将无法编译.

原文地址:https://www.jb51.cc/csharp/100228.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐