简体   繁体   中英

how can i modify a value in list<t>?

    class SomeClass
    {

        private struct PhraseInfo
        {
            public int Start;
            public int Length;
        }

...

        private void SomeMethod(...)
        {
            List<PhraseInfo> posesBracket = new List<PhraseInfo>();
            posesBracket.Add(new PhraseInfo());
            posesBracket[0].Start = 10;
        }

of cause, posesBracket[0].start=10; occur compiler error CS1612 : "Cannot modify the return value of 'expression' because it is not a variable"

how can i modify a value in list?

The problem is that PhraseInfo is a value type, so the this[] method will return a value, not a reference, to solve it, do this:

PhraseInfo pi = posesBracket[0];
pi.Start = 10;
posesBracket[0] = pi;
var temp = posesBracket[0];
temp.Start = 10;
posesBracket[0] = temp;

You cannot have a struct defined as a method. And as they say, you need the reference to change values. So it goes like this:

class SomeClass
    {

        private struct PhraseInfo
        {
            public int Start;
            public int Length;
        }

        private void somemethod()
        {
            List<PhraseInfo> posesBracket = new List<PhraseInfo>();
            posesBracket.Add(new PhraseInfo());
            PhraseInfo pi = posesBracket[0];
            pi.Start = 10;
            posesBracket[0] = pi;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM