简体   繁体   中英

C# Interface Contraints

I am experimenting with Generic Constraints. When declaring a constraint on a class as so:

    public class DocumentPrinter<T> where T : IFooDoc

I am able to access method declared by IFooDoc within the methods of the DocumentPrinter class. However, if I make DocumentPrinter implement an interface that declares the contraint, eg:

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

and then declare DocumentPrinter as so:

   public class DocumentPrinter<T>: IDocumentPrinter<T>

properties/methods of IFooDoc instances are no longer available within the methods of the Document printer. It seems that I must explicitly declare an interface constraint upon the class itself if I am to access members declared by the type.

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?

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?

Correct. You have 1 to declare the constraint on the type parameters for the generic class as well. Just because you named the type parameter in DocumentPrinter<T> to have the same name as the type parameter in IDocumentPrinter<T> does not mean that they are the same types. When you declare

public class DocumentPrinter<T> : IDocumentPrinter<T>

you are in fact saying to use T that parameterizes DocumentPrinter<T> to parameterize IDocumentPrinter<T> and now they are the same types. But for that to be legal, T from DocumentPrinter<T> has to satisfy all constraints on the type parameter for IDocumentPrinter<T> . Thus, you must explicitly say that T satisfies T : IFooDoc .

1 : Apparently I need to state this explicitly. If you don't do something the language specification requires you to do, your code won't compile. The language specification requires that when you parameterize a generic type, the type that you parameterize it with must satisfy all the constraints on that type parameter for that generic type. If you do not, your code won't compile.

properties/methods of IFooDoc instances are no longer available within the methods of the Document printer

Well, it's kind of irrelevant what IntelliSense tells you when your code doesn't compile .

If you want to implement IDocumentPrinter<T> , you have to satisfy its constraint. If you don't, your code won't compile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM