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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...