使用不同的数据类型设置属性值

时间:2013-01-23 17:26:02

标签: c# design-patterns

假设我有一个类,这个类包含一个公共属性,它是一个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年,我相信必须有一种更有说服力的方法来实现这一目标。是否存在,或者首先是一个坏主意?

1 个答案:

答案 0 :(得分:2)

您可以创建一个BitmapFactory类作为工厂来创建Bitmap,您可以阅读有关Factory Design Pattern的更多信息:

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;
    }
}