C#将函数封装进dll,并在应用程序中调用

作为一名小白可能看了很多人介绍方法都不得其意,大概是高手们不屑于写这种简单的博客。今日用到此封装方法,记录下来分享给大家。

一、封装函数
 

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());  
        }  
    }  
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值