I have this code :
public struct SmartFilter
{
public int from, to;
public Arra开发者_如何学运维yList collect = new ArrayList();
public long bit;
}
i get error :
cannot have instance field initializers in structs
i try different way to get over this error without success,
how to have a array list in struct / class?
There are multiple problems there:
- having a mutable struct - just evil
- having public fields
- using
ArrayList
none of these is helping you...
with a class
the initializer would work fine
with a property you could do lazy init:
public ArrayList Collect {
get { return collect ?? (collect = new ArrayList()); }
}
I would refactor to:
public class SmartFilter
{
public int From {get;set;}
public int To {get;set;}
private List<SomeKnownType> collect = new List<SomeKnownType>();
public List<SomeKnownType> Collect { get { return collect; } }
public long Bit {get;set;}
}
Eh, I'll let the guys with bigger brains than me explain why, but you can't do that. :) However you could do this...
class NotAStruct
{
public int from, to;
public ArrayList collect = new ArrayList();
public long bit;
}
...or this...
struct Blah
{
ArrayList doh;
public void SomeMethod()
{
doh = new ArrayList();
}
}
But neither is a good idea, as pointed out by several other people.
You should make a class of it, I wouldn't keep an ArrayList
in a struct since struct should be used for simple data. Regarding the error you have I think you just can remove the new ArrayList();
and it should work.
I wrote this and it works just fine:
public struct MyStruct
{
public int intVal;
public ArrayList listVal;
public bool boolVal;
}
However, I really thing you should use a class instead; that is, use this instead:
public class MyClass {
public int IntVal {get; set;}
public ArrayList ListVal {get; set;}
public bool BoolVal {get; set;}
}
精彩评论