在我的C#控制台应用程序中,我启动一个新任务并调用一个函数,该函数要求我能够访问在主线程中定义的变量,例如:
class Example { static int ExampleVarForQuestion = 1; int Main() { new Task(WhereProblemOccures.ExampleFunction).Start(); } } class WhereProblemOccures { static int ExampleFunction() { if(Example.ExampleVarForQuestion == 1) return 1; else return 0; } }问题是在ExampleVarForQuestion()无法达到上述变量值ExampleVarForQuestion 。 我对C#很陌生,所以如果这个问题没有措辞,那就非常抱歉了。
In my C# console application, I start a new task and call a function that requires me to be able to access variables that were defined in the main thread, for example:
class Example { static int ExampleVarForQuestion = 1; int Main() { new Task(WhereProblemOccures.ExampleFunction).Start(); } } class WhereProblemOccures { static int ExampleFunction() { if(Example.ExampleVarForQuestion == 1) return 1; else return 0; } }The problem is that the above variable value ExampleVarForQuestion is not able to be reached in ExampleVarForQuestion(). I'm quite new to C#, so if this question wasn't worded very good sorry about that.
最满意答案
为了达到它,它必须是公共的,因为你的方法是在另一个类中定义的。
请注意,如果该成员将由另一个线程编写,您应该添加某种形式的同步以保证线程安全。
For it to be reached it must be public as your method is defined in another class.
Note that if the member is going to be written by another thread you should add some form of synchronization to guarantee thread safety.
更多推荐
发布评论