我需要获取一个随机类,存储到一个“全局类”变量中(这样我就可以用其他方法访问它),但我找不到任何好的方法来做到这一点,我一直在尝试做的是使用对象变量...我从 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
}
}
我应该如何解决这个问题?谢谢。
编译器将一个变量类型化为对象,并且所有实例成员都将被编译器验证为有效。另一个变量类型为动态,所有实例成员将被编译器忽略并在执行时由 DLR 调用。
您可以使用dynamic
代替object
public class allMan
{
//Where all classes 'merge'
private dynamic 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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句