문제

이미지 크기를 계산하는 기본 클래스가 있습니다. 나는 그로부터 클래스를 파생시키고 내 코드에 사용될 이미지 크기를 사전 정의했습니다. 내가 가진 것이 작동하는 동안, 나는 제대로하지 않는다는 강한 느낌을 가지고 있습니다.

이상적으로는 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