So I have an object called FixedSizeList that does not have a parameterless constructor.
Looks like this.
class FixedSizeList<T>
{
public FixedSizeList(Int32 size)
{
this.Size = size;
this._Array = new T[size];
}
}
Now I want to use this object as a property of another class as such.
public FixedSizeList<Card> CardList { get; set; }
I have noticed that I can inf开发者_JAVA百科act declare the property with a constructor.
public new FixedSizeList<Card> CardList { get; set; }
But the problem is that the FixedSizeList is not instantiated (I guess for obvious reasons).
So shouldn't I either get a compile time error (something like "No parameterless constructor declared for object") for this code or infact be somehow able to declare the parameter in the property?
Could someone please explain what is going on and if there is someway to fix this problem?(Obviously I can do all this in the constructor of the second object but I am trying to look at other techniques).
Putting new
in front of a property doesn't cause the property's setter to be magically called at initialization time and passed a new instance of that type (that would be quite a load of implications for a tiny little keyword!)
Rather, it's used to hide a member with the same name on a base class.
If you want your property to return a new instance right away, you need to give it a backing that's initialized:
public FixedSizeList<Card> CardList
{
get { return _cardList; }
set { _cardList = value; }
}
private FixedSizeList<Card> _cardList = new FixedSizeList<Card>(99999999);
what you want to do is something of a factory
you need a static method that will return you an instance of the object, inside your class
public static FixedListSize GetInstance() {
return new FixedListSize();
}
I can't remember though if you have to mark the class as static, i think you may have to. it's escaping me at the moment :\
精彩评论