简体   繁体   English

从不同的函数访问类对象

[英]Accessing class objects from different functions

How can I access a class object from different functions?如何从不同的函数访问类对象? So I have:所以我有:

Player player1 = new Player(); Player player1 = new Player();
Player player2 = new Player(); Player player2 = new Player();

Inside my void main function.在我的 void main 函数中。

But when I try to get: player1.name from fight function (a new function I have created) player1 isn't recognized.但是,当我尝试从战斗功能(我创建的新功能)中获取: player1.name 时,无法识别 player1。

How can I share the class player1 between my functions?.如何在我的函数之间共享类 player1?

I can basically give the player1 info to the function 'fight' using function parameters but in case I have 50 parameters to pass it's hard.我基本上可以使用函数参数将 player1 信息提供给函数“fight”,但如果我有 50 个参数要传递,那就很难了。

Thanks everybody!谢谢大家!

I have tried to call the class player1 from different functions but it was an error.我试图从不同的函数调用类 player1 但这是一个错误。

static void Main(string[] args) {
        Player player1 = new Player();
}

public void fight(){
        Console.WriteLine(player1.name);

}

Your question is a matter of scope.你的问题是范围问题。 Depending on where you declare your variables, they are only visible within a certain scope.根据您声明变量的位置,它们仅在特定范围内可见。 There are many sites that explain this concept, but here's one:有很多网站解释了这个概念,但这里有一个:

https://www.geeksforgeeks.org/scope-of-variables-in-c-sharp/https://www.geeksforgeeks.org/scope-of-variables-in-c-sharp/

In answer to your question, you can declare your variables as 'global' and then have access to them in any function in your class.为了回答您的问题,您可以将变量声明为“全局”,然后可以在类中的任何函数中访问它们。

You can make them global by taking your declaration, ie Player player1 = new Player();您可以通过声明将它们设为全局,即 Player player1 = new Player(); and then moving it outside of your void main method, so that it's not inside of any method, but still inside your class.然后将它移到你的 void main 方法之外,这样它就不在任何方法的内部,而是在你的类内部。 You will then be able to access and modify the values of that variable in any function in that class.然后,您将能够在该类中的任何函数中访问和修改该变量的值。

You should also check out access modifiers like private,public, protected, etc. to see how other classes might access those variables.您还应该检查私有、公共、受保护等访问修饰符,以了解其他类如何访问这些变量。

You need to pass the Player object as a parameter to the function fight.您需要将 Player 对象作为参数传递给函数 Fight。 Example:例子:

static void Main(string[] args)
{
    Player player1 = new Player();
}
public void fight(Player player)
{
    Console.WriteLine(player.name);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM