如何在c#中从一个类使用另一个类更改变量



标题可能听起来有点混乱,但我想做的基本上是创建一个类,声明一个public int,默认值为0,然后在Program类I中永久地改变函数中这个变量的值,如果我使用另一个函数打印这个值,它将打印第一个函数中设置的值。例如:

using System;
{
class Global
{
public int variable = 0;
}
class Program
{
static void Main(string[] args)
{
Global test = new Global();
test.variable = 10;
//it makes no sense in this code to use another function, 
//but in my other project it does
Function();
Console.ReadLine();
}

static void Function()
{
Global test = new Global();
//should print 10
Console.WriteLine(test.variable);
}

}

}

如果你不想为注入而烦恼,你可以创建一个静态类:

public static class Global
{
public int variable = 0;
}
class Program
{
static void Main(string[] args)
{
Global.variable = 10;
}
static void Function()
{
Console.WriteLine(Global.variable);
}
}

或者你可以直接将类作为参数从调用它的地方注入。

public class Global
{
public int variable = 0;
}
class Program
{
static void Main(string[] args)
{
var test = new Global();
test.variable = 10;
}
static void Function(Global global)
{
Console.WriteLine(global.variable);
}
}

如果你想在每个类中永久地改变这个变量,你可以使用静态类,但这样你就不能创建它的实例(如果你想让其他变量是非静态的)。

我建议查看IServiceProviders,因为如果Function()方法在另一个类中,并且你想要传递Global类,那么它们真的很有用。

最新更新