我有一个基类,可以对图像大小进行计算。我正在从该类中得出一个类,并且具有预定义的图像大小,这些图像大小将在我的代码中使用。虽然我的工作工作,但我有一种强烈的感觉,我做得不正确。

理想情况下,我只想将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 每当您打电话给它。

其他提示

根据您的需求,您可以通过几种方法来做到这一点。我会考虑执行不同的界面设置。这样的东西。

public interface ISizedPics
{
    int Width {get; }
    int Height {get; }
    void Save(Guid userId)
}
public class ProfilePics, iSizedPics
{
    public int Width { get { return 200; } }
    public int Height { get { return 160; } }
    public void Save(Guid UserId)
    {
        //Do your save here
    }
}

然后,完成此操作,您实际上可以这样使用。

ISizedPics picInstance = new ProfilePics;
Guid myId = Guid.NewGuid();
picInstance.Save(myId);

这只是这样做的一种方法,我喜欢这种方式,因为您可以轻松地围绕此过程创建工厂课程,以帮助您根据需要声明实例。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top