简体   繁体   English

我该如何修改列表中的值 <t> ?

[英]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; of cause,posesBracket [0] .start = 10; occur compiler error CS1612 : "Cannot modify the return value of 'expression' because it is not a variable" 发生编译器错误CS1612:“无法修改'表达式'的返回值,因为它不是变量”

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是一个值类型,所以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;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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