0

假设我有一个类,这个类包含一个公共属性,它是一个 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,我相信一定有一个更雄辩的方法来实现这一点。有没有,或者这首先是一个坏主意?

4

1 回答 1

2

您可以创建一个BitmapFactory充当工厂的类来创建一个Bitmap,您可以阅读有关工厂设计模式的更多信息:

public class TestClass
{
    public BitmapFactory BitmapFactory { get; set; }
    public Bitmap Bitmap { get { return this.BitmapFactory.Bitmap; } }
}

public interface IBitmapFactory
{
    Bitmap Bitmap { get; }
}

public class BitmapFactory : IBitmapFactory
{
    public Bitmap Bitmap { get; private set; }

    public BitmapFactory(Bitmap value)
    {
        this.Bitmap = value;
    }

    public BitmapFactory(BitmapImage value)
    {
        this.Bitmap = ConvertBitmapImageToBitmap(value);
    }

    public BitmapFactory(WriteableBitmap value)
    {
        this.Bitmap = ConvertWriteableBitmapToBitmap(value);
    }

    private Bitmap ConvertWriteableBitmapToBitmap(WriteableBitmap value)
    {
        //do work here
        return null;
    }

    private Bitmap ConvertBitmapImageToBitmap(BitmapImage value)
    {
        //do work here
        return null;
    }
}
于 2013-01-23T17:47:14.467 回答