![](/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.