【发布时间】:2018-06-11 19:50:01
【问题描述】:
我需要一个随机类,存储到一个“全局类”变量中(这样我就可以用其他方法访问它),但是我找不到任何好的方法来做,我一直在尝试做正在使用对象变量...我是从 python 到 c#,所以对象变量的属性对我来说看起来有点神秘...我一直在寻找如何使它工作,但我找不到合适的没有一堆 if 语句的方法......
//There might not be all the necessary namespaces to run this code
using UnityEngine; //where the random.range() came from
public class man1 //Initialization of the first class
{
public int val = 1;
}
public class man2 //Initialization of the second class
{
public int val = 2;
}
public class man3 //Initialization of the third class
{
public int val = 3;
}
public class allMan
{ //Where all classes 'merge'
private object chosenMan; //Where the chosen it's going to be stored
public allMan() //Constructor
{
//Have all man in one array to easily get the chosen from index
object[] men = new object[] { new man1(), new man2(), new man3() };
var choice = Random.range(0, men.Length); //Randomly get the index
chosenMan = men[choice]; // Atribute the chosen class
}
public void doActionWithChoosedMan()
{
Console.WriteLine(chosenMan.val); //ERROR
}
}
我应该如何解决这个问题?谢谢。
【问题讨论】:
-
类 man1、man2 和 man3 没有提供足够的细节来说明您为什么会这样做。您介意使用 man1、2 和 3 的另一个示例,它们的功能与您实际想要的类似,说明您这样做的原因吗?
-
你可能只是有一个非常糟糕的例子。但是,如果所有类共享共同特征,则创建一个基类来表示共同特征并让所有类都派生自共同基类。然后,您将选择的对象作为基类类型。
-
尝试以下匿名定义:var men = new { man1 = new man1(), man2 = new man2(), man3 = new man3() };
-
它是一个(伪)随机数生成器,那么为什么不能在需要它们的地方创建任意数量的随机数呢?输出不会改变