封装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”

猜你喜欢

转载自blog.csdn.net/ido1ok/article/details/82992192