如何使 dll 中的代码适应主代码?

How can I adapt the code in dll to the main code?

我正在尝试调整我在 dll 中找到的函数,但我是使用 dll 和划分代码的新手。 dll中的代码是:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace gdll
{
    public class Class1
    {
        private Bitmap DoGray(Bitmap bmp)
        {
            for (int i = 0; i < bmp.Height - 1; i++)
            {
                for (int j = 0; j < bmp.Width - 1; j++)
                {
                    int value = (bmp.GetPixel(j, i).R + bmp.GetPixel(j, i).G + bmp.GetPixel(j, i).B) / 3;
                    Color clr;
                    clr = Color.FromArgb(value, value, value);
                    bmp.SetPixel(j, i, clr);
                }
            }
            return bmp;
        }
    }

}

但是form1.cs中的代码应该怎么写呢? Form1.cs[设计]有两个按钮和2个pictureBox.The第一个按钮是原图,第二个是过滤后的picture.I写了没有dll的代码版本(我把函数写到同一页)以下:

private void button2_Click(object sender, EventArgs e)
        {
            Bitmap image= new Bitmap(pictureBox1.Image);
            Bitmap gray = DoGray(image);
            pictureBox2.Image = gray;
        }

在dll文件中运行当然是不行的。

这是 form1.cs 处的代码:




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using gdll;


namespace dnmimage
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            sfd.Filter = "Image Files|*.bmp|All Files|*.*";
            sfd.InitialDirectory = ".";
            if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            pictureBox1.ImageLocation = sfd.FileName;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Bitmap image= new Bitmap(pictureBox1.Image);
            Bitmap gray = DoGray(image);
            pictureBox2.Image = gray;
        }

DoGray 函数是私有的。为了使其在 Class1 之外可见,它必须是 public. Further you should make it static:

public static Bitmap DoGray(Bitmap bmp)

下一步是引用需要从 WinForms 项目(具有 Form1.cs 文件的那个)引用的 gdll dll(具有您的 DoGray 函数的那个​​)。 最简单的方法是将两个项目(WinForms 项目和 dll 项目)放在同一个解决方案中,并使用一个项目 reference.

然后右键单击您的 WinForms 项目(包含您的 Form1.cs 文件的项目)和 select“添加引用…

在左侧的“Reference Manager”select“Projects”中勾选你的gdll(有Class1.cs文件的那个)然后点击ok。

现在您可以使用 DoGray 函数了:

private void button2_Click(object sender, EventArgs e)
{
    Bitmap image= new Bitmap(pictureBox1.Image);
    Bitmap gray = gdll.Class1.DoGray(image);
    pictureBox2.Image = gray;
}