作为一名小白可能看了很多人介绍方法都不得其意,大概是高手们不屑于写这种简单的博客。今日用到此封装方法,记录下来分享给大家。
一、封装函数
1、打开VS,新建C#库类,输入一下代码:
namespace test
{
public class msg
{
public int Tip()
{
return 1 + 1;
}
}
}
2、点击生成,在项目文件夹中bin/Debug下就可一看到一个dll文件,此文件就是封装了我们刚才的函数。
二、调用dll中函数
1、新建一个WPF应用程序项目,随便建一个按钮,添加点击事件
<Window x:Class="test1.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>
2、调用dll中函数
using System.Windows;
using test;
namespace test1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
//实例化
msg test = new msg();
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//调用dll中方法
int i = test.Tip();
MessageBox.Show(i.ToString());
}
}
}
3、运行,点击按钮,看到返回值就是2。
三、其他
1、函数声明为静态是可直接调用,不用实例化
namespace test
{
public class msg
{
public static int Tip()
{
return 1 + 1;
}
}
}
using System.Windows;
using test;
namespace test1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
//实例化
//msg test = new msg();
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//调用dll中方法
int i = msg.Tip();
MessageBox.Show(i.ToString());
}
}
}