我在VS 2017中输入以下代码:
namespace Test {
class MyClass {
public static Random randomkey;
static MyClass() {
randomkey = new Random();
}
public MyClass() {
randomkey = new Random();
}
public int returnkey() => randomkey.Next();
}
class Program {
private static void Main(string[] args) {
try {
Console.WriteLine(MyClass.randomkey.Next());
var x = new MyClass();
Console.WriteLine(x.returnkey());
var y = new MyClass();
Console.WriteLine(y.returnkey());
Console.ReadLine();
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
}
}
然后点击“调试”按钮,我发现结果很奇怪:
Output - The same random number
然后,我尝试单击“运行到光标”按钮,结果变得不同:
Output - Different random numbers
为什么?
答案 0 :(得分:-1)
随机函数使用系统时间来初始化随机数发生器。因此,快速运行代码会得到相同的随机数。添加一个睡眠,然后你会得到预期的结果。
export class Users {
public users: IUser[] = [];
_users: Observable<IUser[]>;
constructor() {
let users = [
// your dummy data
];
for (let user of users) {
this.users.push(new IUser(user));
}
this._users = Observable.of(this.users);
}
validLogin(accountInfo: IUser): Observable<IUser> {
return this._users.map((user:IUser) =>
user.filter((user:IUser) => user.usernanme == accountInfo.username && user.password == accountInfo.password);
}
}