You can put the data at the class level instead of an ephemeral local scoped variable:
class Program
{
static public Weapon bSword { get; } = new Weapon();
static void InitializeWeapon()
{
BSword.name = "Bronze Sword";
Console.WriteLine(bSword.name); //works fine
}
static void Main(string[] args)
{
InitializeWeapon();
Console.WriteLine(BSword.name);
WeaponShop();
Console.ReadLine();
}
...
}
Therefore it will be accessible inside the class and from outside in read-only mode here, as a composite.
It seems you want to manage several weapons, so you can for example use a List:
public class Weapon
{
public string Name { get; set; }
}
class Program
{
static public List<Weapon> Weapons { get; } = new List<Weapon>();
static void InitializeWeapons()
{
Weapons.Add(new Weapon { Name = "Bronze Sword" });
Weapons.Add(new Weapon { Name = "Silver Sword" });
foreach ( var weapon in Weapons )
Console.WriteLine(weapon.Name);
}
static void Main(string[] args)
{
InitializeWeapons();
ShopWeapon();
Console.ReadLine();
}
static void ShopWeapon()
{
foreach ( var weapon in Weapons )
{
Console.WriteLine($"Buy {weapon.Name}?");
// ...
}
}
}
What Are OOP Concepts?
What is abstraction in C#?
How to choose between public, private and protected access modifier?
What is polymorphism?
What is the difference between an interface and a class?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…