1. 程式人生 > >封裝C#程式碼為DLL並在C#程式碼中引用

封裝C#程式碼為DLL並在C#程式碼中引用

1.封裝C#程式碼為DLl

在VS2012中建立專案選擇類庫,命名testMyDll,新建類msg,注意修飾符必須為public

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testMyDll
{
    public class msg
    {
        public int add(int x, int y)
        {
            return x + y;
        }
    }
}

點選專案生成解決方案,然後在專案目錄的bin/debug下即可發現封裝好的dll檔案

2,新建WPF專案testUseMyDll,在引用裡新增testMyDll專案封裝好的類庫.

WPF主介面上新增一個按鈕

<Window x:Class="testUseMyDll.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="211,116,0,0" Click="Button_Click_1"/>

    </Grid>
</Window>

後臺程式碼引用DLL類庫

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using testMyDll;

namespace testUseMyDll
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            msg test = new msg();
            MessageBox.Show(test.add(1, 5)+"");
        }
    }
}

執行後新增按鈕彈出視窗“6”