如何以可以从 C# 中的其他方法访问的方式存储随机类变量?

凯克·桑托斯

我需要获取一个随机类,存储到一个“全局类”变量中(这样我就可以用其他方法访问它),但我找不到任何好的方法来做到这一点,我一直在尝试做的是使用对象变量...我从 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在其他方法中调用变量

是否可以从其他方法访问变量?

如何从Java中的其他方法访问对象?

使变量可以被C中的其他函数访问

将Angular4图片上传到s3存储桶并存储响应。将位置存储到全局变量中,可以访问其他方法/函数

C#,如何使用WebAPI在类中创建变量,然后可以在其他类中引用这些变量?

如何从其他方法引用变量?

可以通过其他方法访问的另一个类的Objective-C属性

有没有其他方法可以在C ++中填充数组而无需向量

如何在C ++中的其他类的方法中访问变量

如何以其他方式变形数据

如何访问其他类中的变量

C#App是否可以访问其他类的变量?

是否可以在运行时使用Reflection API或其他方式访问方法的局部变量?

如何以数组或其他方式存储图像并一个接一个地检索

如何以其他方式编写此查询

您如何使方法内部产生的变量可用于类中的所有其他方法?

如何使用UIBezierPath或任何其他方法在Objective-C中以编程方式创建如下所示的自定义矩形?

是否有其他方法可以将 DI 容器引用存储在 Application 变量中?

如何从类的其他方法访问该方法?

在Objective-C 中,如何让@property 可以被其他类访问?

访问其他 Windows 窗体类 C# 中的变量

如何访问objective c的其他模块中的swift类

使 Django 中的其他方法(和视图)可以访问一种方法的上下文变量

在 WPF/C# 中,如何访问动态生成控件的元素或以其他方式向它们添加单击事件?

如何在 C# 中调用此方法和调用其他方法?

如何将变量存储在特征中,以便可以在特征的其他方法中使用?

除了文本文件或csv文件之外,还有其他方法可以将数据存储在c中吗?

我不了解 C++ 中的这一行 [[ MyBook(string t,string a,int price):Book(t,a) ]] 以及如何以其他方式编写此代码?