博客
关于我
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 - 类 __hash__ 方法和集合
查看>>
Python - 轻松将文本文件内容转换为字典值/键
查看>>
Python - 递归和列表
查看>>
python -- 小数据池 is和 == 再谈编码
查看>>
Python 3 中未定义名称“xrange“
查看>>
python进阶(5):魔术方法篇(1)
查看>>
Python 3 范围与 Python 2 范围
查看>>
Python 3 读取ini文件
查看>>
Python 3.0 使用 turtle.onclick
查看>>
Python 3.10 明年发布,看看都有哪些新特性?
查看>>
python 3.10上安装pyqt5
查看>>
Python 3.12 正式发布了!
查看>>
Python 3.2 中的蛮力脚本
查看>>
Python 3.4 多处理递归 Pool.map()
查看>>
Python 3.4:未知格式代码“x“
查看>>
Python 3.5、ldap3 和 modify_password()
查看>>
python 3.6.8 升级至3.9版本升级
查看>>
Python 3.9 到 Python 3.12 的发展历程与区别
查看>>