如何将对象分配给字段

本文关键字:字段 分配 对象 | 更新日期: 2023-09-27 18:09:40

我不知道该怎么命名

我有一个类是这样的:

class exampleClass
{
    string 1 = "Sth1";
    string 2 = "Sth2";
    string 3 = "Sth3";
    int tmp;
}

我想在第二类中分配字段:

obj = new examplelass ();

obj.tmp = 3;

在第三类中调用tmp字段:

if(obj.tmp == 3) show me string number 3 -> "Sth3".

的结论。我不知道怎么把这个tmp和string联系起来。我希望它是一个enum类型的

如何将对象分配给字段

字典应该适合你的需求

Dictionary<int, string> myDict = new Dictionary<int, string>();
myDict.Add(1, "Sth1");
myDict.Add(2, "Sth2");
myDict.Add(3, "Sth3");
string Result = myDict[3]; //Sth3

将对象与小的连续数字相关联的最直接的方法是数组或列表:

class exampleClass {
    // An object associated with int value X goes into X-th position:
    private static readonly string[] Strings = new[] {"Sth1", "Sth2", "Sth3"};
    // Since tmp is used as an index, you need to protect assignments to it:
    private int tmp;
    public int Tmp {
        get { return tmp; }
        set {
            if (value < 0 || value >= Strings.Length) {
                throw new ArgumentOutOfRangeException();
            }
            Tmp = value;
        }
    }
    public string GetString() {
        return Strings[tmp];
    }
}

注意Tmp添加的setter,它确保调用者不能为tmp分配负值或高于字符串数组中最后允许的索引的值。

这看起来像是数据结构的作业。

你拥有的是多个变量。您想要的是一个集合。像这样:

class ExampleClass
{
    public IList<string> Strings = new List<string> { "Sth0", "Sth1", "Sth2", "Sth3" };
}

然后可以通过索引来引用元素:

var obj = new ExampleClass();
obj.Strings[3] // <--- will be "Sth3"

如果索引由于某种原因需要在对象上存储,您可以使用您现在拥有的int:

class ExampleClass
{
    public IList<string> Strings = new List<string> { "Sth0", "Sth1", "Sth2", "Sth3" };
    public int CurrentIndex;
}

var obj = new ExampleClass { CurrentIndex = 3 };
obj.Strings[obj.CurrentIndex] // <--- will be "Sth3"

添加更多的错误检查,改进变量名称(因为给定当前名称,确实不清楚您的总体目标是什么),甚至将其演变成一个适当的迭代器结构,等等

首先,注意123不是有效的字段名或enum名。所以我们把它们叫做ABC

enum MyOption { A, B, C }

class MyClass
{
    public MyOption Option { get; set; }
}
var obj = new MyClass();
obj.Option = MyOption.A;
if(obj.Option == MyOption.A)
{
    // ...
}