C # interface weaknesses

I am experimenting with General restrictions. When declaring a constraint for a class as follows:

public class DocumentPrinter<T> where T : IFooDoc 

I can access the method declared by IFooDoc in the methods of the DocumentPrinter class. However, if I make DocumentPrinter an implemented interface that declares this restriction, for example:

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

and then declare DocumentPrinter as follows:

  public class DocumentPrinter<T>: IDocumentPrinter<T> 

IFooDoc instance properties / methods are no longer available within Document printer methods. It seems that I should explicitly declare an interface restriction for the class itself if I want to access members declared by the type.

Do I understand this correctly or can I declare a restriction on the interface and get this restriction implemented by the class?

+7
source share
2 answers

Do I understand this correctly or can I declare a restriction on the interface and get this restriction implemented by the class?

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

 public class DocumentPrinter<T> : IDocumentPrinter<T> 

you are actually saying that you are using T , which parameterizes DocumentPrinter<T> to parameterize IDocumentPrinter<T> , and now they are the same types. But in order to be legal, the T from DocumentPrinter<T> must satisfy all the restrictions on the type parameter for IDocumentPrinter<T> . So you must explicitly say that T satisfies T : IFooDoc .

1 : Apparently, I need to state this explicitly. If you do not do something that is required for the language specification, your code will not compile. The language specification requires that when parameterizing a generic type, the type that you parameterize must satisfy all the restrictions of this parameter for this type. If you do not, your code will not compile.

+8
source

IFooDoc instance properties / methods are no longer available in document printer methods

Well, it doesn't matter what IntelliSense tells you when your code does not compile .

If you want to implement IDocumentPrinter<T> , you need to satisfy its limitation. If you do not, your code will not compile.

+3
source

All Articles