在不同的类上使用相同的对象,同时保留一个对象的内容 [英] Using the same object on different classes while keeping content of one object

查看:82
本文介绍了在不同的类上使用相同的对象,同时保留一个对象的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having 3 classes. First class is a Authorize class which have get/set property for User and Pass. Second, Add class is creating new instance of Authorize class and assigning a value from it's textboxes to the properties by using initializing new object:

Authorize authorize = new Authorize();

第三个类Display试图从类Authorize获得属性User和Pass的值.问题是我不能在此处使用Authorize的新对象,因为它将清空第一个创建的对象的内容.

Third class, Display, is trying to get the value of property User and Pass from class Authorize. The problem is that I can not use here a new object of Authorize, because it will empty the content of first created object.

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

如何避免/更改此设置,以便可以从不同的类访问同一对象?这是一个理论上的例子.我正在编写代码,但时间太长了.如果需要,我可以在这里发布.但是现在我照原样离开了.

How can I avoid/change this so I can access the same object from different class? This is a theoretical example. I am working on code but it's lengthily. If needed, I can post it here. But for now I leave as it is.

如果我不够清楚,请提出问题.

Please ask questions if I am not clear enough.

强烈建议使用假人示例:)

Examples for dummies highly recommended :)

致谢

-编辑-一些代码:

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作为添加类

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减少为Authorize类.

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;
            }
        }
    }
}

推荐答案

您在问题中已进行了更多说明,因此我将尝试解决.

You've given a bit more clarification in your question, so I'll try to address it.

在主表单中,使您的代码执行以下操作:

In the main form, make your code do something like this:

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中,创建一个result属性,并在单击OK并填写所有数据时进行设置:

In the AuthorizeWindow, make a result property, and set it when you click OK and have filled in all the data:

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时,将存储的身份验证传递给它:

Then on the main form, when you create and open the AddEntryWindow, pass it the authentication you stored:

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

但是,糟糕,我在这里创建了一个小错误.我们应该检查他们是否先经过身份验证:

But oops, I've created a small bug here. We should check if they've authenticated first:

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代码中发现了一个小错误.确保所有Windows的所有构造函数始终调用InitializeComponent.在这种情况下,编辑使用用户名和密码的构造函数以调用默认构造函数,就像其他使用MainWindow的构造函数一样:

Also, I found a small bug in your AddEntryWindow code. Make sure that all the constructors for all your windows always call InitializeComponent. In this case, edit the constructor that takes a username and password to call the default constructor, like your other constructor that takes a MainWindow does:

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

编辑前:

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

I don't completely understand your example code. It would be easier if you would create new code samples to add to your question.

不过,这是我从你所说的中得到的:

Here's what I got from what you've said, though:

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的实例传递给Display类中的Show方法(或您实际调用的任何方法).只需接受Authorize的实例作为该方法的参数即可:

The easiest way to do this is to pass the instance of Authorize to the Show method (or whatever you are actually calling it) in your Display class. Just accept an instance of Authorize as an argument to that method:

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);
    }

    // ...
}

这篇关于在不同的类上使用相同的对象,同时保留一个对象的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆