C#:将派生类作为参数传递 [英] C#: Pass derived class as parameter

查看:169
本文介绍了C#:将派生类作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类,可以计算图像大小。我从中派生一个类,并具有将在我的代码中使用的预定义图像大小。虽然我的工作正常,但我有一种强烈的感觉,那就是我做得不好。

I have a base class that does calculations on image sizes. I'm deriving a class from that and have predefined image sizes that will be used in my code. While what I have works, I have a strong feeling that I'm not doing it properly.

理想情况下,我只想将DerviedClass.PreviewSize作为参数传递

Ideally, I'd like to just pass DerviedClass.PreviewSize as the parameter to GetWidth without having to create an instance of it.

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 -具有始终返回相同值的实现似乎很没有意义。另一方面,我可以看到,您想要一种简单的方法来获取始终用于预览的尺寸。我会这样:

It seems to me that you want a more flexible implementation of ISize - having an implementation which always returns the same value seems fairly pointless. On the other hand, I can see that you want an easy way of getting the size that you always use for a preview. I would do it like this:

// 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 的相同实例每当您调用它时。

This would reuse the same instance of FixedSize whenever you called it.

这篇关于C#:将派生类作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆