从列表

时间:2019-02-14 07:27:40

标签: c# arraylist ref

我有一个变量,然后将该变量添加到列表中。如果我将list [0]设置为null,则将其从列表中删除,并且变量仍然保持不为空。

如果我将变量设置为null,则列表中的那个就不为null。

    var s = new String("Test".ToCharArray()); //Example of class

    var list = new List<String>();

    list.Add(s);

A:

    s = null;

    Debug.Log( list[0] ); //Test
    Debug.Log( s ); //Null

B:

    list[0] = null;

    Debug.Log( list[0] ); //Null
    Debug.Log( s ); //Test

我的实际代码更加复杂,包含多个变量和对象,一些变量将实例保存到同一对象(都不是结构),其中一个包含所有对象的列表。

执行'list [0] = null'仅清空该列表中的第0个位置,而不是使该对象为null,我也希望将该对象设置为null。

我希望A和B都将它们都设为空。有人可以解释为什么它不那样做,以及如何使其那样做吗?

并且由于列表包含对s的引用,为什么's = null'不会将列表项更改为null?

2 个答案:

答案 0 :(得分:1)

List添加到string时,您只是传递项目的值,而不传递对象本身。 一种实现方法是将public class wrapper { public string Str{get; set;} public wrapper(str s) { Str = s; } } 包裹在另一个对象中:

Str

通过使用此对象代替,如果更新对象的List属性,则它也将在var s = new Wrapper("Buzz"); var l = new List<Wrapper>(); l.Add(s); s.Str = null; 中更改,因为列表指向包含该值的此类。

这是您的示例,但正在使用中。

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

        RadioGroup rg1,rg2;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            rg1 =(RadioGroup)findViewById(R.id.rg1);
            rg2 =(RadioGroup)findViewById(R.id.rg2);

            rg1.setOnCheckedChangeListener(this);
            rg2.setOnCheckedChangeListener(this);
        }
        int radioId1 = 0,radioId2 = 0;
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {

            if (radioGroup == rg1){

                radioId1 = i;
            }
            if (radioGroup == rg2){
                radioId2 = i;
            }

            if (radioId1 != 0 && radioId2 != 0){
                RadioButton radioButton1 = (RadioButton) findViewById(radioId1);
                RadioButton radioButton2 = (RadioButton) findViewById(radioId2);
                Toast.makeText(this,radioButton1.getText()+" and "+radioButton2.getText()+" is selected",Toast.LENGTH_LONG).show();
            }
        }
    }

答案 1 :(得分:1)

如评论中所述,这不是C#的工作方式。特别是,C#不允许直接将对对象的引用存储为另一个对象的一部分。因此,以下方法将起作用:

class Variable<T>
{
   public Variable(T value) { Value = value; }
   public T Value { get; set; }
}

var s = new Variable<string>("Test");
var list = new List<Variable<string>>();

list.Add(s);

那么你有一个

s.Value = null;

Debug.Log( list[0].Value ); //Null
Debug.Log( s.Value ); //Null

和B

list[0].Value = null;

Debug.Log( list[0].Value ); //Null
Debug.Log( s.Value ); //Null