繁体   English   中英

如何将条件与类匹配(实现接口)并调用其应用方法

[英]How to match condition with a class(implements interface) and call its apply method

在我的控制台应用程序中,我有一个名为IFileConverter的接口,如下所示:

public interface IFileConverter
{
    string InputFileFormat { get; }
    string OutputFileFormat { get; }
    object Convert(object input);
}

而部分实现该接口的class模板有: Png2JpgConverter class 代码为;

/// <summary>
/// Image of class of converter Png file to Jpg file.
/// </summary>
public class Png2JpgConverter : IFileConverter
{
    public string InputFileFormat => "png";

    public string OutputFileFormat => "jpg";

    public object Convert(object input) => "this is a jpg file.";   // TODO ...
}

另一个 class 例如: Jpg2BmpConverter class 代码是;

/// <summary>
/// Image of class of converter Jpg file to Bmp file.
/// </summary>
public class Jpg2BmpConverter : IFileConverter
{
    public string InputFileFormat => "jpg";

    public string OutputFileFormat => "bmp";

    public object Convert(object input) => "this is a bmp file.";   // TODO ..
}

我有InputFileFormat这是: string inputFileFormat = "png";

OutputFileFormat即: string outputFileFormat = "jpg";

object 是object input = "this is a png file.";

我的问题是; 我想调用适当的 class 的Convert()方法进行虚拟转换过程。 但我需要在有效操作中做到这一点。 有没有办法像下面给出的那样做?

static void Main(string[] args)
    {
        string inputFileFormat = "png";
        string outputFileFormat = "jpg";
        object input = "this is a png file."; // for example


        //here i want to call method of Convert() like this:
        if(var selectedConverter is IFileConverter converter)
        {
            object output = selectedConverter.Convert(input);
        }
        // but i don't know how to do it and how to match inputFileFormat and outputFileFormat
        // in appropriate class that impelents IFileConverter interface...
    }

你能帮忙的话,我会很高兴..

如果我明白你的意思,我认为“多态性”的概念在这种情况下会有所帮助

var converters = new List<IFileConverter> {new Jpg2BmpConverter(), new Png2JpgConverter()};

var outputList = new List<object>();

foreach (var fileConverter in converters)
{
    outputList.Add(fileConverter.Convert(input));
}

现在你有了一个输出列表,你可以用它做你想做的事。

memory 中的图像只是一个矩阵宽度 X 高度 X 通道。 PNG 和 JPG 是用于将这些矩阵保存在磁盘上的压缩方法。

想要转换磁盘文件吗?

bmp -> png 示例

string filepath = "PathToBMPImage.bmp";
string savePath = "PathToPngOutout.png";
//Load the image, don't use new System.Drawing.Bitmap(string path) because it'll convert the image in 32BPP
using(var bmp = (System.Drawing.Bitmap)System.Drawing.Image.FromFile(filepath))
 //Now inside bmp there is a matrix WxHxC
 bmp.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);

所有 GDI 编码器和解码器都在这里 您可以将参数添加到编码器参数,例如 jpg 压缩。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM