我有一个基类来计算图像大小.我正在从中派生一个类,并具有将在我的代码中使用的预定义图像大小.虽然我有所作为,但我有一种强烈的感觉,我没有正确地做到这一点.
理想情况下,我想将DerviedClass.PreviewSize作为参数传递给GetWidth,而不必创建它的实例.
class Program
{
    static void Main(string[] args)
    {
        ProfilePics d = new ProfilePics();
        Guid UserId = Guid.NewGuid();
        ProfilePics.Preview PreviewSize = new ProfilePics.Preview();
        d.Save(UserId, PreviewSize);
    }
}
class ProfilePicsBase
{
    public interface ISize
    {
        int Width { get; }
        int Height { get; }
    }
    public void Save(Guid UserId, ISize Size)
    {
        string PicPath = GetTempPath(UserId);
        Media.ResizeImage(PicPath, Size.Width, Size.Height);
    }
}
class ProfilePics : ProfilePicsBase
{
    public class Preview : ISize
    {
        public int Width { get { return 200; } }
        public int Height { get { return 160; } }
    }
}
在我看来,你想要一个更灵活的实现ISize- 拥有一个总是返回相同值的实现似乎毫无意义.另一方面,我可以看到你想要一个简单的方法来获得你用来预览的大小.我会这样做:
// Immutable implementation of ISize
public class FixedSize : ISize
{
    public static readonly FixedSize Preview = new FixedSize(200, 160);
    private readonly int width;
    private readonly int height;
    public int Width { get { return width; } }
    public int Height { get { return height; } }
    public FixedSize(int width, int height)
    {
        this.width = width;
        this.height = height;
    }
}
然后你可以写:
ProfilePics d = new ProfilePics();
Guid userId = Guid.NewGuid();
d.Save(userId, FixedSize.Preview);
FixedSize无论何时调用它,都会重用相同的实例.