Class Initialization Using Generics

I have a Document class that has two overloads that take one parameter each (String and Stream). Why can't I use the following code to initialize a Document class using Generics?

    public abstract class PdfDocumentEditBaseService<T> : IDocumentEditService<T>

    public T Rotate(T file, int pageNumber, float angle)
    {
        Document document = new Document(file); // cannot convert from 'T' to 'Stream'
        document.Pages[pageNumber].Rotation = (RotationMode)angle;
        document.SavePage(pageNumber);
        return file;
    }
+3
source share
4 answers

I see some suggestions requiring T to inherit from Stream. And it will work. But, if your T is really always a thread, why not just remove the general parameter and build this class as follows:

public abstract class PdfDocumentEditBaseService : IDocumentEditService
{
    public Stream Rotate(Stream file, int pageNumber, float angle)
    {
        Document document = new Document(file); 
        document.Pages[pageNumber].Rotation = (RotationMode)angle;
        document.SavePage(pageNumber);
        return file;
    }
+1
source

You can do this if you change your ad to:

public abstract class PdfDocumentEditBaseService<T> : IDocumentEditService<T> where T : Stream
+3
source

:

public abstract class PdfDocumentEditBaseService<T> : IDocumentEditService<T>
                                            where T : Stream
+2

, Document , Stream Stream. , , T .

If you add a type constraint to the class declaration, this should work:

public abstract class PdfDocumentEditBaseService<T> : IDocumentEditService<T> where T : Stream
0
source

Source: https://habr.com/ru/post/1731024/


All Articles