Let’s say I have a class, this class contains a public property which is a System.Drawing.Bitmap, but I want the consumer of my class to be able to set this value with a number of different types of image, without really having to think about what they are passing in, I will do the conversions neccessary behind the scenes. This is what I mean:
var myBitmapImage = new BitmapImage();
var writeableBitmap = new WriteableBitmap(myBitmapImage);
var mySystemDrawingBitmap = new Bitmap(@"A:\b.c");
var classOne = new TestClass();
var classTwo = new TestClass();
var classThree = new TestClass();
//This should work:
classOne.MyImage = myBitmapImage;
//This should also work:
classTwo.MyImage = writeableBitmap;
//This should work too
classThree.MyImage = mySystemDrawingBitmap;
At the moment I am thinking of something like this:
public class TestClass
{
private Bitmap _myImage;
public object MyImage
{
get
{
return _myImage;
}
set
{
if (value is Bitmap)
{
_myImage = (Bitmap)value;
}
if (value is BitmapImage)
{
var imageAsSystemDrawingBitmap = ConvertBitmapImageToBitmap((BitmapImage)value);
_myImage = imageAsSystemDrawingBitmap;
}
if (value is WriteableBitmap)
{
var imageAsSystemDrawingBitmap = ConvertWriteableBitmapToBitmap((WriteableBitmap)value);
_myImage = imageAsSystemDrawingBitmap;
}
throw new Exception("Invalid image type");
}
}
private Bitmap ConvertWriteableBitmapToBitmap(WriteableBitmap value)
{
//do work here
return null;
}
private Bitmap ConvertBitmapImageToBitmap(BitmapImage value)
{
//do work here
return null;
}
}
But using an object and casting feels very 2001, and I am sure there must be a more eloquent way to achieve this. Is there, or is this a bad idea in the first place?
You could create a
BitmapFactoryclass that behaves as a factory to create aBitmap, you can read more about the Factory Design Pattern: