C#在多个类中使用变量

时间:2018-05-17 19:49:09

标签: c#

我的问题是内部类变量是否有任何公共方式可以在多个类中使用?

示例:当用户键入新密码时,我有一个名为password的变量。我想这样做,这个变量可以发送到我的用户名类,所以我可以对它们进行总结:用户名:HeyIamCool |密码:hello123。

using System;

namespace Project{

    public static class Password {

        public static void Main() {

            Console.WriteLine("Please enter your new password");

            string password = Console.ReadLine();
            Console.WriteLine("Are you sure you want to change your password to: " + password + "? (Yes/No)");
            string input = Console.ReadLine();

            if(input.ToLower() == "yes") 
            {
                Console.WriteLine("Your password has been changed to " + password + "!");
                Console.WriteLine("Press any key to continue..");
                Console.ReadKey();
                Console.Clear();
                Username.Name ();

            }
            else if(input.ToLower() == "no")
            {
            Console.WriteLine(password + " will not be saved as your password");
            Console.WriteLine("Press any key to restart");
            Console.ReadKey();
            Console.Clear();
            Main();
            //System.Environment.Exit(0);

            }

            else 
            {
            Console.WriteLine("ERROR! Press any key to restart");
            Console.ReadKey();
            Console.Clear();
            Main ();
            }
        }




    }
    public static class Username 
    {
        public static void Name () 
        {
        Console.WriteLine("Please enter a username you would like");
        Console.ReadLine();
        }



    }
}

2 个答案:

答案 0 :(得分:2)

您可以将变量本身设置为public:

public string password = "password";

或者您可以将其保密并为其编写一个getter函数:

private string password = "password";

public string GetPassword()
{
    return password;
}

然后,当您想要检索它时,您只需创建一个密码类实例

Password pass = new Password();

string myPassword = pass.password;  //if you used a public variable

string myPassword = pass.GetPassword(); //if you used a private variable

答案 1 :(得分:0)

虽然我们无法通过您的问题提供明确的答案,但我们可以使用反射从其外部访问成员变量:

public class Example
{
    public static void Main(string[] args)
    {
        var target = new Mistery();
        foreach (var field in target.GetType().GetFields(BindingFlags.Instance | 
                                                         BindingFlags.NonPublic))
        {
            Console.WriteLine("{0}={1}", field.Name, field.GetValue(target));
        }
    }
}

public class Mistery
{
    private string _secret = "hello123";
}

您也可以谈论继承,您可以在base类中定义某些成员,并在derivate类中使用它们。

public class MyBase
{
    protected string Secret = "hello123";
}

public class MyDerived : MyBase
{
    public void DoSomething()
    {
        Console.WriteLine(Secret);  // Will write the secret variable value
    }
}