开发者

How to assign a variable name to each index of an array?

开发者 https://www.devze.com 2023-03-12 07:14 出处:网络
public string[] TestResults = new string[8]; I want to assign each item of the array above to a variable. For example,
public string[] TestResults = new string[8];

I want to assign each item of the array above to a variable. For example,

TestName = TestResults[0];
开发者_Go百科

I am getting the message: A field initializer cannot reference the non static field, method or property" when I do the following:

public string TestName = TestResults[0];

Please suggest me how can I resolve this.


You can't do that in a variable initializer, basically... although the value would be null anyway. You can't refer to this within a variable initializer, so you'd have to write:

public class Foo 
{
    // I hope your fields aren't really public...
    public string[] TestResults = new string[8];

    public string TestName;

    public Foo()
    {
        TestName = TestResults[0];
    }
}

Note that this would only retrieve the value at construction anyway. It wouldn't associate the variable itself with the first element in the array; either could change without affecting the other. If you want TestName to always be associated with TestResults[0] you might want to use a property instead:

public class Foo
{
    // I hope your fields aren't really public...
    public string[] TestResults = new string[8];

    public string TestName
    {
        get { return TestResults[0]; }
        set { TestResults[0] = value; }
    }
}


You seem to assume that, if your code worked, TestName becomes an alias for TestResults[0], such that reading from or writing to that variable also changes the array. This is not the case.

What you can do, is using a property for this:

public string[] TestResults;

public MyClass()
{
    TestResults = new string[8];
}

public string TestName
{
    get { return TestResults[0]; }
    set { TestResults[0] = value; }
}


If you are looking to have a synonym for the index of the array you can use the following:

public string TestName
{
    get { return TestResults[0]; }
    set { TestResults[0] = value; }
}

This creates a set of methods called a property that are called in a syntax similar to a variable. You can drop the set part if you don't want write access externally.

If you want a copy of the variable you will need to write to it at some other point such as in the constructor.


This happens because

public string TestName = TestResults[0];

Will set TestName to the same instance of string that is stored in TestResults[0]. In other words, TestName will be a reference to the object stored in TestResults[0], not a reference to the memory address that is TestResults[0].

Depending on how your code is set up, I would just use properties and their getters:

public string TestName
{
    get { return TestResults[0]; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消