C#类与类库调用注意事项

创建一个类文件,myfunction.cs

//静态类:直接引用、无需实例化
static public int jiafa(int V)
//普通类:引用时需要实例化
public int jiafa(int V)

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace OPC_Client
{
    **class myfunction**
    {
        //静态类:直接引用、无需实例化
        //static public int jiafa(int V)
        //普通类:引用时需要实例化
        public int jiafa(int V)
        {
            int M = 2;
            int W = V + M;
            return W;
        }
        //普通类:引用时需要实例化
        public int chengfa(int V)
        {
            int M = 2;
            int W = V * M;
            return W;
        }
        //普通类:引用时需要实例化
        public int jianfa(int V)
        {
            int M = 2;
            int W = V - M;
            return W;
        }
        //普通类:引用时需要实例化
        public int chufa(int V)
        {
            int M = 2;
            int W = V / M;
            return W;
        }
        public static bool IsRuning(string exeName)
        {
            bool res = false;
            //if (Process.GetProcessesByName(exeName).Length > 0)
            if (Process.GetProcessesByName(exeName).ToList().Count > 0)
            {
                res = true;
            }
            return res;
        }

        public static float fValue = 10;


        public static decimal dValue = 10;
        public static int xiancheng1 = 10;
        public static int xiancheng2 = 10;
        public static int xiancheng3 = 10;
    }
}

另一个类HBIS.cs中调用类myfunction.cs

myfunction szys = new myfunction();//实例化

using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OPCAutomation;
using System.Diagnostics;
using System.Threading;
using System.IO;//Thread.Sleep(5000);


namespace OPC_Client
{

    public partial class HBIS : Form
    {
        OPCServer objServer;
        OPCGroups objGroups;
        OPCGroup objGroup;
        OPCItems objItems;
        Array strItemIDs;
        Array lClientHandles;
        Array lserverhandles;
        Array lErrors;
        //int ltransID_Rd = 1;
        //int lCancelID_Rd;
        object RequestedDataTypes = null;
        object AccessPaths = null;
        //Array lerrors_Rd;
        Array lErrors_Wt;
        static int r_items = 13;
        static int w_items = 7;

        int lTransID_Wt;
        int lCancelID_Wt;
        public HBIS()
        {
            InitializeComponent();
        }

        bool isrun = false;//
        //连接opc server
        private void button1_Click(object sender, EventArgs e)
        {
            //(1)创建opc server对象
            objServer = new OPCServer();
            //连接opc server
            objServer.Connect("KingView.View.1", null);//KEPware.KEPServerEx.V4
            //(2)建立一个opc组集合
            objGroups = objServer.OPCGroups;
            //(3)建立一个opc组
            objGroup = objGroups.Add(null); //Group组名字可有可无
            //(4)添加opc标签
            objGroup.IsActive = true; //设置该组为活动状态,连接PLC时,设置为非活动状态也一样
            objGroup.IsSubscribed = true; //设置异步通知
            objGroup.UpdateRate = 250;
            objServer.OPCGroups.DefaultGroupDeadband = 0;
            objGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);
            //objGroup.AsyncReadComplete += new DIOPCGroupEvent_AsyncReadCompleteEventHandler(AsyncReadComplete);
            //objGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(AsyncWriteComplete);
            objItems = objGroup.OPCItems; //建立opc标签集合
            string[] IntmpIDs = new string[r_items];
            int[] tmpCHandles = new int[r_items];
            for (int i = 1; i < r_items; i++)
            {
                tmpCHandles[i] = i;
            }

            //组态王读和写变量数据共计12个
            for (int i = 1; i < r_items; i++)
            {
                IntmpIDs[i] = "Tag_" + i + ".Value";
            }

            strItemIDs = (Array)IntmpIDs;//必须转成Array型,否则不能调用AddItems方法
            lClientHandles = (Array)tmpCHandles;
            // 添加opc标签
            objItems.AddItems(r_items - 1, ref strItemIDs, ref lClientHandles, out lserverhandles, out lErrors, RequestedDataTypes, AccessPaths);
        }


        //结束并断开opc server
        private void button4_Click(object sender, EventArgs e)
        {
            objServer.Disconnect();
            //关闭kepserver进程,这个跟OPC操作无关
            /*
            foreach ( Process oneProcess in Process.GetProcesses())
            {
            if (oneProcess.ProcessName == "ServerMain")
            oneProcess.Kill();
            }
            */
        }
        
        //每当项数据有变化时执行的事件,采用订阅方式
        myfunction szys = new myfunction();
        void KepGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
        {          
            //数据交换【读取组态王共计6个变量数据】
            //组态王------>label、label------>textBox
            for (int i = 0; i < NumItems; i++)
            {
                int cHandles = Convert.ToInt32(ClientHandles.GetValue(i + 1));

                switch (cHandles)
                {
                    case 1: 
                        this.Data1.Text = ItemValues.GetValue(i + 1).ToString();
                        this.textBox1.Text = szys.jiafa(Convert.ToInt32(this.Data1.Text)).ToString();
                        break;
                    case 2:
                        this.Data2.Text = ItemValues.GetValue(i + 1).ToString();
                        this.textBox2.Text = szys.chengfa(Convert.ToInt32(this.Data2.Text)).ToString();
                        break;
                    case 3:
                        this.Data3.Text = ItemValues.GetValue(i + 1).ToString();
                        this.textBox3.Text = szys.jianfa(Convert.ToInt32(this.Data3.Text)).ToString();
                        break;
                    case 4:
                        this.Data4.Text = ItemValues.GetValue(i + 1).ToString();
                        this.textBox4.Text = szys.chufa(Convert.ToInt32(this.Data4.Text)).ToString();
                        break;
                    case 5:
                        this.Data5.Text = ItemValues.GetValue(i + 1).ToString();
                        this.textBox5.Text = szys.chengfa(Convert.ToInt32(this.Data5.Text)).ToString();
                        break;
                    case 6:
                        this.Data6.Text = ItemValues.GetValue(i + 1).ToString();
                        this.textBox6.Text = szys.jianfa(Convert.ToInt32(this.Data6.Text)).ToString();
                        break;
                    default:
                        ;
                        break;
                }

                //myfunction.fValue = 100;

            }
        }

        //发送异步写数据指令
        //textBox------>组态王
        private void button3_Click(object sender, EventArgs e)
        {
            Array AsyncValue_Wt;
            Array SerHandles;
            object[] tmpWtData = new object[w_items];//写入的数据必须是object型的,否则会报错  3-->7
            int[] tmpSerHdles = new int[w_items]; //3-->7
            //将输入数据赋给数组,然后再转成Array型送给AsyncValue_Wt           

            tmpWtData[1] = this.textBox1.Text;
            tmpWtData[2] = this.textBox2.Text;
            tmpWtData[3] = this.textBox3.Text;
            tmpWtData[4] = this.textBox4.Text;
            tmpWtData[5] = this.textBox5.Text;
            tmpWtData[6] = this.textBox6.Text;
            
            AsyncValue_Wt = (Array)tmpWtData;

            //将输入数据送给的Item对应服务器句柄赋给数组,然后再转成Array型送给SerHandles
            //组态王写变量数据共计6个
            tmpSerHdles[1] = Convert.ToInt32(lserverhandles.GetValue(7));
            tmpSerHdles[2] = Convert.ToInt32(lserverhandles.GetValue(8));
            tmpSerHdles[3] = Convert.ToInt32(lserverhandles.GetValue(9));
            tmpSerHdles[4] = Convert.ToInt32(lserverhandles.GetValue(10));
            tmpSerHdles[5] = Convert.ToInt32(lserverhandles.GetValue(11));
            tmpSerHdles[6] = Convert.ToInt32(lserverhandles.GetValue(12));

            lTransID_Wt = w_items - 1;
            SerHandles = (Array)tmpSerHdles;
            objGroup.AsyncWrite(w_items - 1, ref SerHandles, ref AsyncValue_Wt, out lErrors_Wt, lTransID_Wt, out lCancelID_Wt);//2-->6 
        }

        //异步写入成功
        //private void AsyncWriteComplete(int TransactionID, int NumItems, ref Array ClientHandles, ref Array Errors)
        //{
        //    //MessageBox.Show("数据写入成功!");
        //}

        private void button2_Click(object sender, EventArgs e)
        {
            //本质:分配新的内存空间来显示新的窗体
            //方法一:
            //Form fm2 = new stati();//实例化窗体2对象
            //fm2.Show();//调用窗体2对象的显示方法
            //方法二
            //new stati().Show();//直接实例化,并调用实例对象的窗体显示功能
            
            //登录验证
            if (textBox7.Text == "123456")
            {
                //MessageBox.Show("登录成功");
                //new stati().Show();
                //隐藏当前窗体(this)
                //this.Hide();//方法一
                //Hide();//方法二

                //采用委托新线程的方法实现第二个窗体(stati)的跳转
                //Thread t1 = new Thread(delegate() { new stati().ShowDialog(); });
                //t1.Start();
                //Dispose();//方法一
                //Close();//方法二

                //标记法
                //1、程序启动类中自定义一个标记
                //2、判断标记为"验证成功"后才显示第二个窗体
                //3、监控何时关闭第一个窗体(HBIS),当关闭第一个窗体前,应先将标记变为"验证成功"
                Program.success_flag = "验证成功";
                Close();

            }else {
                MessageBox.Show("登录失败");
            }                        
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //登录验证
            if (textBox7.Text == "123456")
            {
                //采用委托delegate新线程的方法实现第二个窗体(stati)的跳转
                Thread t2 = new Thread(delegate() { new ftplt().ShowDialog(); });
                t2.Start();
                Dispose();         
            }
            else
            {
                MessageBox.Show("登录失败");
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //登录验证
            if (textBox7.Text == "123456")
            {
                //采用委托delegate新线程的方法实现第二个窗体(stati)的跳转
                Thread t3 = new Thread(delegate() { new mForm().ShowDialog(); });
                t3.Start();
                Dispose();         
            }
            else
            {
                MessageBox.Show("登录失败");
            }
        }
    }
}

类库

新建类库 Algorithm,类math2必须用public修饰

区分myfunction与math2的区别

class myfunction//类 
public class math2//类库,带public,否则另一类库无法访问

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

namespace Algorithm
{
    **public class math2//类库,带public,否则另一类库无法访问**
    {


        //静态类:直接引用、无需实例化
        //static public int jiafa(int V)
        //普通类:引用时需要实例化
        public int jiafa2(int V)
        {
            int M = 2;
            int W = V + M;
            return W;
        }
        //普通类:引用时需要实例化
        public int chengfa2(int V)
        {
            int M = 2;
            int W = V * M;
            return W;
        }
        //普通类:引用时需要实例化
        public int jianfa2(int V)
        {
            int M = 2;
            int W = V - M;
            return W;
        }
        //普通类:引用时需要实例化
        public int chufa2(int V)
        {
            int M = 2;
            int W = V / M;
            return W;
        }



        

        public static float fValue = 10;


        public static decimal dValue2 = 10;
        public static int xiancheng12 = 10;
        public static int xiancheng22 = 10;
        public static int xiancheng32 = 10;
    }
}

在主类库OPC_Client中添加引用类库Algorithm

然后在调用类库Algorithm的类文件中Using Algorithm

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
**using Algorithm;**
namespace OPC_Client
{
    //class class_var
    //{
    //    public static int Numglobal1;
        
    //}

    public partial class ftplt : Form
    {
        public ftplt()
        {
            InitializeComponent();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://mp.csdn.net");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            
            if (tabControl1.TabPages[btn.Text]==null)
            {
                tabControl1.TabPages.Add(btn.Text, btn.Text);
                if (btn.Text == "一号锅炉") 
                {
                    Form frm = new boiler1();
                    frm.TopLevel = false;
                    frm.Dock = DockStyle.Fill;
                    frm.FormBorderStyle = FormBorderStyle.None;
                    frm.Show();
                    tabControl1.TabPages[btn.Text].Controls.Add(frm);
                }
                else if (btn.Text == "二号锅炉")
                {
                    Form frm = new boiler2();
                    frm.TopLevel = false;
                    frm.Dock = DockStyle.Fill;
                    frm.FormBorderStyle = FormBorderStyle.None;
                    frm.Show();
                    tabControl1.TabPages[btn.Text].Controls.Add(frm);
                }
                //else if()
                //{}

            }
            tabControl1.SelectedTab = tabControl1.TabPages[btn.Text];
        }
        
        private void timer1_Tick(object sender, EventArgs e)
        {
            //if (myfunction.xiancheng1 < 60)
            //    myfunction.xiancheng1++;
            //else
            //    myfunction.xiancheng1 = 0;
            //lblglobal1.Text = myfunction.xiancheng1.ToString();


            if (math2.xiancheng12 < 60)
                math2.xiancheng12++;
            else
                math2.xiancheng12 = 0;
            lblglobal1.Text = math2.xiancheng12.ToString();
        }

    }
}

代码和上位机实时读写PLC架构流程:https://download.csdn.net/download/weixin_37928884/88317574

上位机编程参考资料

C#多线程开发-线程间通讯

https://blog.csdn.net/zls365365/article/details/122678135

c#与S7.net通讯实际工程应用

https://blog.csdn.net/flowsea123/article/details/129464477

C#三种定时器Timer详解

https://blog.csdn.net/qq_57798018/article/details/128243618

C# winform textbox PLC寄存器读写功能实现

https://blog.csdn.net/wint_1996/article/details/130596525

相关推荐
向宇it7 小时前
【unity小技巧】unity 什么是反射?反射的作用?反射的使用场景?反射的缺点?常用的反射操作?反射常见示例
开发语言·游戏·unity·c#·游戏引擎
九鼎科技-Leo8 小时前
什么是 WPF 中的依赖属性?有什么作用?
windows·c#·.net·wpf
Heaphaestus,RC9 小时前
【Unity3D】获取 GameObject 的完整层级结构
unity·c#
baivfhpwxf20239 小时前
C# 5000 转16进制 字节(激光器串口通讯生成指定格式命令)
开发语言·c#
直裾9 小时前
Scala全文单词统计
开发语言·c#·scala
ZwaterZ11 小时前
vue el-table表格点击某行触发事件&&操作栏点击和row-click冲突问题
前端·vue.js·elementui·c#·vue
ZwaterZ13 小时前
el-table-column自动生成序号&&在序号前插入图标
前端·javascript·c#·vue
SRC_BLUE_1715 小时前
SQLI LABS | Less-55 GET-Challenge-Union-14 Queries Allowed-Variation 2
oracle·c#·less
yngsqq16 小时前
037集——JoinEntities连接多段线polyline和圆弧arc(CAD—C#二次开发入门)
开发语言·c#·swift
Zԅ(¯ㅂ¯ԅ)16 小时前
C#桌面应用制作计算器进阶版01
开发语言·c#