博客
关于我
C# 多个class之间共享变量
阅读量:789 次
发布时间:2019-03-24

本文共 1592 字,大约阅读时间需要 5 分钟。

C#中的变量管理与C++有所区别,因为它不支持全局变量的概念。因此,所有变量都需要放置在某个类中。为了保证类A和类B能够互相访问和修改变量,可以采取以下两种方法来实现数据传递和变量更新。

方法一:通过静态变量实现变量共享

为了实现类A和类B之间的变量共享,可以定义一个全局类(Global Variable),将其设为公共类,供所有类引用。这样,类A和类B都可以访问并修改这些变量。具体实现方式如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace P
{
static class GlobalVariable
{
public static bool CornerInfoFlag = true;
public static bool RTArrayInfoFlag = true;
public static bool RTLineInfoFlag = true;
public static bool RTGuaiJiaoInfoFlag = true;
public static bool SideArrayInfoFlag = true;
public static bool SideLineInfoFlag = true;
}
}

方法二:通过类A的静态变量进行数据传递

另一种方法是,在类A中定义静态变量,并提供public方法供类B在修改数据后调用。类B在完成计算后,通过调用类A的方法,将最新数据写入类A的静态变量中。这样可以避免全局变量的多处修改问题。示例代码如下:

public class A
{
private static List
Dot = new List
();
public void WriteData(List
threadDot)
{
Dot.InsertRange(0, threadDot);
}
}
public class B : Thread
{
byte[] data;
private List
threadDot = new List
();
private Vector3 xyz;
private readonly A mainThreadData;
public B(byte[] buffer)
{
data = buffer;
mainThreadData = new A();
}
public void ThreadProc()
{
xyz.x = BitConverter.ToSingle(data, 0);
xyz.y = BitConverter.ToSingle(data, 4);
xyz.z = BitConverter.ToSingle(data, 8);
threadDot.Add(xyz);
mainThreadData.WriteData(threadDot);
}
}

这种方法通过类A的静态变量实现了变量的传递和更新,保证了数据的一致性和安全性。

转载地址:http://cjekk.baihongyu.com/

你可能感兴趣的文章
Python中方括号和括号括起来的列表有什么区别?
查看>>
python中时间处理_Python中处理时间的几种方法小结
查看>>
Python中枚举串口(包括虚拟端口)的跨平台方法是什么?
查看>>
python中根号下a怎么写_python中根号怎么表示
查看>>
Python中正则表达式的巧妙使用
查看>>
Python中浮点数的二进制表示(位不是十六进制)
查看>>
Python中特殊函数和表达式 filter,map,reduce,lambda
查看>>
python中用socket检测端口_Python 用socket模块实现检测端口和检测web服务
查看>>
python中用于列表操作的plus和append有什么区别?
查看>>
python中用递归求和
查看>>
python中的@staticmethod
查看>>
python中的array函数作用_NumPy 数组使用大全
查看>>
python中的isinstance判断多个对象类型
查看>>
python中的keys、values、items
查看>>
Python中的lambda和apply结合使用
查看>>
python中的map函数
查看>>
Python中的numpy模块解析
查看>>
Python中的pickle
查看>>
Python中的signal模块和Ctrl+C操作
查看>>
python中的sort方法
查看>>