![](/img/trans.png)
[英]How can I access values in another class inherited from public class C#?
[英]How can I make the randomString answer public so i can access it from another class
我需要生成的随机答案才能从另一个 class 访问。 我的目标是在另一个 class 中给出提示,所以我已经有一个人 class ,我有变量,我需要得到随机答案并为用户获取变量和 output 它们。
static void PopulatePersons()
{
person p1 = new person("Bill", "Brown", false, "m");
person p2 = new person("Eric", "Brown", true, "m");
person p3 = new person("Robert", "Blue", false, "m");
person p4 = new person("George", "Brown", true, "m");
person p5 = new person("Herman", "Green", false, "m");
person p6 = new person("Anita", "Blue", false, "f");
person p7 = new person("Maria", "Green", true, "f");
person p8 = new person("Susan", "Brown", false, "f");
person p9 = new person("Claire", "Brown", true, "f");
person p10 = new person("Anne", "Brown", false, "f");
List<person> personList = new List<person>();
personList.Add(p1);
personList.Add(p2);
personList.Add(p3);
personList.Add(p4);
personList.Add(p5);
personList.Add(p6);
personList.Add(p7);
personList.Add(p8);
personList.Add(p9);
personList.Add(p10);
foreach (person p in personList)
Console.WriteLine(p.GetData());
}
}
public static void GetRandomPerson()
{
Random r = new Random();
int index = r.Next(personList.Count);
person randomString = personList[index];
}
如果你想要随机值,你应该使用一个随机的 object 而不是每次都创建它。
private static Random _random = new Random();
public static void GetRandomPerson()
{
int index = _random.Next(personList.Count);
person randomString = personList[index];
}
您需要公开 randomString 变量。 我建议简单地从 GetRandomPerson() 方法返回它。
public static void GetRandomPerson()
{
int index = _random.Next(personList.Count);
return personList[index];
}
你会从你的其他 class 中调用它
person theRandomPerson = [StaticClassName].GetRandomPerson();
其中 [StaticClassName] 是您的 class 的名称,您未包含该名称。
一些注意事项: person
应该是 C# 中的Person
(类名以大写开头)。
您的 PopulatePerson() 方法可以被清理,并且您在每次调用列表时都在创建和处理该列表。
将列表移动到 static 字段或属性中:
private static List<Person> PersonList;
并在 static 构造函数中实例化它。
static StaticClassName()
{
PersonList = new List<Person>();
// might as well fill it as well;
PopulatePerson();
}
这将使其持久化,因此您只需创建一次列表。
接下来,去掉变量 p1-p10。 您可以将列表填充为:
personList.Add(new person("Bill", "Brown", false, "m"));
...
这将消除 10 行。 每当您创建变量 x1, x2, ... , x10... 时,您都应该停下来想想是否有更好的数据结构可以使用。 至少,使用数组,但在这种情况下,将对象直接扔到列表中就绰绰有余了。
最后,我将打印循环移动到它自己的方法中。 它似乎是调试代码,这绝对没问题,但是您希望轻松删除此代码。 在这种特殊情况下,注释掉这些行还不错。 但是,随着您的编程变得越来越复杂,您需要培养一种个人风格来处理调试。
设置另一种方法
// Used for debugging
static void DumpPersonList()
{
foreach (person p in personList)
Console.WriteLine(p.GetData());
}
并在适当的地方调用它。 这样,您只需注释掉一行即可删除转储,未来的程序员可能会感激您在 class 中为他们提供了这个工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.