假设我有一个类,这个类包含一个公共属性,它是一个 System.Drawing.Bitmap,但我希望我的类的使用者能够使用许多不同类型的图像设置这个值,而不必真的想想他们传递了什么,我将在幕后进行必要的转换。这就是我的意思:
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;
目前我正在考虑这样的事情:
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;
}
}
但是使用一个对象和铸造感觉很 2001,我相信一定有一个更雄辩的方法来实现这一点。有没有,或者这首先是一个坏主意?