开发者

List of structs - the value of the struct items is always null

i have a list of structs : user_stocks = new List<stock_Str>();

the struct is defined:

public struct stock_Str
{
    public String name;
    public int quote ;
    public int chenge;
    public bool quote_a;
    public bool chenge_a;   
    public int[] rate_alarm;   
    public int[] chenge_alarm;
}

when i add item to the list i do:

stock_Str str = new stock_Str();
str.name = tbStockName.Text;
str.chenge_a = false;
str.quote_a = false;
str.quote = 0;
str.chenge = 0;
str.chenge_alarm = new int[2];
str.rate_alarm = new int[2];

for (int i = 0; i < 2; i++)
{
    str.rate_alarm[i] = 0;
    str.chenge_alarm[i] = 0;
}

_mainApp.user_stocks.Add(str)开发者_运维知识库;

my problems:

  1. when i try to change values of the list items(of type struct), it don't change them!

  2. my two arrays of two int's always set to null!

how can i fix it?


a: that should not be a struct, at all b: the "value" of a struct is never null; even Nullable<T>'s null is a bit of a magic-trick with smoke, mirrors and misdirection

Re the problem;

1: yes, that is because structs have copy semantics; you have altered a copy - not the same one

2: probably the same thing

Here's a more appropriate implementation; I imagine it'll fix most of your problems:

public class Stock
{
    public string Name {get;set;}
    public int Quote {get;set;}
    public int Chenge {get;set;}
    public bool QuoteA {get;set;}
    public bool ChengeA {get;set;}
    public int[] RateAlarm {get;set;}
    public int[] ChengeAlarm {get;set;}
}

I'm unclear what the intent of the last 2 is, but personally I would prefer a list if it is a dynamic collection, for example:

    private List<int> rateAlarms;
    public List<int> RateAlarms {
        get { return rateAlarms ?? (rateAlarms = new List<int>()); }
    }


A struct is a Value type so you never get a reference of it to do edits only the copy.

Also you should use a class here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜