سؤال

لدي فئة أساسية تقوم بعمل حسابات على أحجام الصور. أنا اشتقاق فئة من ذلك ولدي أحجام صور محددة مسبقا والتي سيتم استخدامها في التعليمات البرمجية الخاصة بي. في حين أن ما أعمل به، لدي شعور قوي بأنني لا أفعل ذلك بشكل صحيح.

من الناحية المثالية، أود فقط تمرير 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