在保留一个对象的内容的同时在不同的类上使用相同的对象

时间:2011-11-04 04:38:55

标签: c# winforms object parameters

我有3节课。 First类是一个Authorize类,它具有User和Pass的get / set属性。其次,Add class正在创建Authorize类的新实例,并使用初始化新对象将其文本框中的值赋给属性:

Authorize authorize = new Authorize();

第三类,Display,试图从类授权中获取属性User和Pass的值。问题是我不能在这里使用Authorize的新对象,因为它会清空第一个创建对象的内容。

// Can not do, because the object will be discarded and new one created.
Authorize authorize = new Authorize();

如何避免/更改此设置以便我可以从不同的类访问同一个对象?这是一个理论上的例子。我正在研究代码,但它很长。如果需要,我可以在这里发布。但是现在我离开了。

如果我不够清楚,请提问。

强烈推荐假人的例子:)

此致

- 编辑 - 部分代码:

AddEntryWindow.sc作为展示类

namespace Store_Passwords_and_Serial_Codes
{
    public partial class AddEntryWindow : Form
    {
        private string user, pass;

        // Initializind ArrayList to store all data needed to be added or retrived.
        static private ArrayList addedEntry = new ArrayList();

        // Initializing MainWindow form.
        MainWindow mainWindow;

        // Making authentication possible.
        // AuthenticateUser authenticateUser = new AuthenticateUser();

        EncryptDecrypt en = new EncryptDecrypt();

        // Default constructor to initialize the form.
        public AddEntryWindow()
        {
            InitializeComponent();
        }

        public AddEntryWindow(MainWindow viaParameter) : this()
        {
            mainWindow = viaParameter;
        }

        public AddEntryWindow(string user, string pass)
        {
            this.user = user;
            this.pass = pass;
        }

        private void btnAddEntry_Click(object sender, EventArgs e)
        {
            // Making sure that type is selected.
            if {}
            else
            {
                // reason why I need the content of AuthenticationUser content.
                string encrypted = en.Encrypt(stringBuilder.ToString(), user, pass);
                string decrypted = en.Decrypt(encrypted, user, pass);

                MessageBox.Show(user + pass);
                    //encrypted + Environment.NewLine + decrypted;

                /*mainWindow.ChangeTextBox = stringBuilder.ToString() + Environment.NewLine +
                    "Encrypted" + Environment.NewLine +
                    encrypted + Environment.NewLine +
                    "Decrypted" + Environment.NewLine +
                    decrypted + Environment.NewLine;
                */
            }
        }

        public static void ShowMe(AuthenticateUser au)
        {
            au.UserName = user;
            au.Password = pass;
        }

        private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Deciding which data must be entered depending on
            // what type is selected from combo box.

            // PC
            // Web Site
            // Serial Code
        }
    }
}

AuthenticationWindow.cs为Add class

namespace Store_Passwords_and_Serial_Codes
{
    public partial class AuthenticationWindow : Form
    {
        public AuthenticationWindow()
        {
            InitializeComponent();
        }

        private void btnAuthenticate_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)
            {
                MessageBox.Show("Please fill both information first.");
            }
            else
            {
                AuthenticateUser au = new AuthenticateUser();

                au.UserName = txtUserName.Text;
                au.Password = txtPassword.Text;

                AddEntryWindow.ShowMe(au);

                MessageBox.Show(au.UserName + au.Password);

                Close();
            }
        }
    }
}

不太重要的AuthenticateUser.cs作为授权类。

using System;

namespace Store_Passwords_and_Serial_Codes
{
    public class AuthenticateUser
    {
        private string userName, password;

        public AuthenticateUser()
        {
        }

        public AuthenticateUser(string userNamePassed, string passwordPassed)
        {
            this.userName = userNamePassed;
            this.password = passwordPassed;
        }

        public string UserName
        {
            get
            {
                return userName;
            }
            set
            {
                userName = value;
            }
        }

        public string Password
        {
            get
            {
                return password;
            }
            set
            {
                password = value;
            }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

修改

你在问题​​中给出了更多的澄清,所以我会尝试解决它。​​

在主窗体中,让代码执行以下操作:

private AuthenticateUser storedAuth; // shared data...

private void btnLogin_Click(object sender, EventArgs e)
{
    AuthorizeWindow authWindow = new AuthorizeWindow();
    authWindow.ShowDialog();
    storedAuth = authWindow.Result; // Get the auth result back...
}

AuthorizeWindow中,创建一个结果属性,并在单击“确定”并填写所有数据时进行设置:

public AuthenticateUser Result { get; set; }

private void btnAuthenticate_Click(object sender, EventArgs e)
{
    if (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)
    {
        MessageBox.Show("Please fill both information first.");
    }
    else
    {
        // Don't try to call the other window here, just set the result and close...
        Result = new AuthenticateUser();
        Result.UserName = txtUserName.Text;
        Result.Password = txtPassword.Text;

        Close();
    }
 }

然后在主窗体上,当您创建并打开AddEntryWindow时,将您存储的身份验证传递给它:

private void btnAdd_Click(object sender, EventArgs e)
{
    AddEntryWindow addWindow =
        new AddEntryWindow(storedAuth.User, storedAuth.Password);
    addWindow.ShowDialog();
}

但是哎呀,我在这里创造了一个小虫子。我们应该先检查一下他们是否已经过验证:

private void btnAdd_Click(object sender, EventArgs e)
{
    if(storedAuth == null)
    {
        MessageBox.Show("You must log in before you add an entry");
    }
    else
    {
        AddEntryWindow addWindow =
            new AddEntryWindow(storedAuth.User, storedAuth.Password);
        addWindow.ShowDialog();
    }
}

另外,我在您的AddEntryWindow代码中发现了一个小错误。确保所有窗口的所有构造函数始终调用InitializeComponent。在这种情况下,编辑带有用户名和密码的构造函数来调用默认构造函数,就像采用MainWindow的其他构造函数一样:

public AddEntryWindow(string user, string pass)
    : this() // important!
{
    this.user = user;
    this.pass = pass;
}

编辑前:

我不完全理解您的示例代码。如果您要创建新的代码示例以添加到您的问题中会更容易。

这是我从你所说的话中得到的,但是:

public class Authorize
{
    public string Username { get; set; }
    public string Password { get; set; }
}

public class Add
{
    public void Login()
    {
        Authorize authorize = new Authorize();
        authorize.Username = usernameTextBox.Text;
        authorize.Password = passwordTextBox.Text;
        // Todo: Rest of login logic here
    }

    // Todo: Other code here...
}

public class Display
{
    public void Show()
    {
        Authorize authorize = new Authorize();
        // uh oh, Username and Password are null!
    }

    // Todo: Other code here...
}

<强>解决方案

执行此操作的最简单方法是将Authorize的实例传递到Show类中的Display方法(或您实际调用的任何方法)。只需接受Authorize的实例作为该方法的参数:

public class Display
{
    public void Show(Authorize authorize)
    {
        // Now we have the values that the Login method created...
    }

    // ...
}

public class Add
{
    public void Login()
    {
        Authorize authorize = new Authorize();
        authorize.Username = usernameTextBox.Text;
        authorize.Password = passwordTextBox.Text;
        display.Show(authorize);
    }

    // ...
}

答案 1 :(得分:0)

有两种方法可以实现您的目标。第一种方法是将一个Authority实例传递给将使用它的所有不同方法。我认为由于某种原因这是禁止的,否则你已经在做了。有一种名为singletons的设计模式可能对您正在做的事情有用。链接页面有一些代码示例。

答案 2 :(得分:0)

作为参数传递是最好的解决方案,如果你在传递参数时遇到问题,那么去授权作为属性(设置/获取),这样你就可以摆脱参数传递问题。如果这也是问题,那么使用Singleton Pattern或者创建Static class。