简体   繁体   English

用户应该是类还是结构数组?

[英]Should Users be class or arrays of structures?

I can't understand if I am doing code in right way. 我无法理解我是否以正确的方式编写代码。 I have vibed application. 我申请了签证。

Code inside main: main内部的代码:

User user = new User(database);
user.getUserByName("admin");

User Class: 用户类别:

class User
{
    string login;
    string password;

    //....
    void getUserByName(string login)
    {
        // sql request here
        this.login = row[1].coerce!string;
        this.password = row[2].coerce!string;
    }
    //...
}

How long on instance of class will be live? 类实例将存活多长时间? For example 3 users come to my site: David, Jow, Mike, so getUserByName would be called 3 times. 例如,有3个用户访问了我的站点:David,Jow,Mike,因此getUserByName将被调用3次。

user.getUserByName("David");
user.getUserByName("Jow");
user.getUserByName("Mike");

Does it mean that with every new logging users class fields login and password would be overwritten in my code? 这是否意味着对于每个新的日志记录用户类字段, loginpassword都会在我的代码中被覆盖? It's seems yes. 好像是 But is it good? 但这好吗? Or would I have any problem like this: 还是我有这样的问题:

for example if the field in instance of class would be initialized by David and then second user will login and field would be changed by Jow ? 例如,如果class实例中的字段由David初始化,然后第二个用户登录并且Jow将更改该字段?

I decided to check my idea. 我决定检查一下我的想法。 And did: 并做了:

    void getUserByName(string login)
    {
        writeln("login before: ", login);
        Prepared prepared = prepare(database.connection, `SELECT id, login, password, usergroup from users WHERE login=?`);
        Thread.sleep(1.seconds); // pause till new getUserByName with another name will be called (as I think)
        prepared.setArgs(login);
        ResultRange result = prepared.query();
    ...
}

and in main : 并且main

user.getUserByName("David");
user.getUserByName("Jow"); // calling another

But it's very strange that I am getting: 但是我很奇怪:

login before: David
login after: David
login before: Jow
login after: Jow

But I expected that after calling (second): user.getUserByName("Jow"); 但是我希望在调用第二个之后: user.getUserByName("Jow"); and after sleep I will get something like: sleep后我会得到类似的东西:

login before: David
login after: Jow

And I can't understand why... 我不明白为什么...

Another variant as I understand is make users as structure and create new copy of structure for every user. 据我了解,另一个变体是将用户作为结构并为每个用户创建结构的新副本。 Is it good? 好吗? Or maybe there is another better solution? 也许还有另一个更好的解决方案?

writeln("login before: ", login);

That login does not refer to the login field of the class, because you have an argument named login . login不引用该类的login字段,因为您有一个名为login的参数。 If you want the class field you'll need: 如果要使用class字段,则需要:

writeln("login before: ", this.login);

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

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