Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Calling Methods in Generic Classes

I am extending the ImageBox control from EmguCV. The control's Image property can be set to anything implementing the IImage interface.

All of the following implement this interface:

Image<Bgr, Byte>
Image<Ycc, Byte>
Image<Hsv, Byte>

Now I want to call the Draw method on the object of the above type (what ever it may be).

The problem is when I access the Image property, the return type is IImage. IImage does not implement the Draw method, but all of the above do.

I believe I can cast the object of type IImage to one of the above (the right one) and I can access the Draw method. But how do I know what the right one is? If you have a better way of doing this, please suggest that as well.

EDIT

Sorry, but I forgot to mention an important piece of information. The Draw method for each of the above class takes one different argument. For e.g. Draw for Image<Bgr, Byte> takes an argument of type Bgr and the Draw for Image<Hsv, Byte> takes an argument of type Hsv instead.

like image 644
Aishwar Avatar asked Mar 14 '10 20:03

Aishwar


1 Answers

Add an IDrawableImage that inherits from IImage.

public interface IDrawableImage : IImage
{
   void Draw(object val);
   void Draw();
}

Then you can simply do the following:

var drawableImage = container.Image as IDrawableImage;
if (drawableImage != null)
    drawableImage.Draw();

To match your clarification above:

public interface IDrawableImage<T, B> : IDrawableImage where B : byte
{
    void Draw<T>(T val);
}

then if you know the type:

var value = new Hvr();
var drawableImage = container.Image as IDrawableImage<Hvr, Byte>;
if (drawableImage != null)
    drawableImage.Draw(value);

if you don't

var value = new Hvr();
var drawableImage = container.Image as IDrawableImage;
if (drawableImage != null)
    drawableImage.Draw(value);
like image 128
Tom Anderson Avatar answered Oct 12 '22 01:10

Tom Anderson