C# 对象,该对象没有无参数构造函数作为类的属性
因此,我有一个名为FixedSizeList的对象,它没有无参数构造函数C# 对象,该对象没有无参数构造函数作为类的属性,c#,syntax,constructor,properties,C#,Syntax,Constructor,Properties,因此,我有一个名为FixedSizeList的对象,它没有无参数构造函数 public new FixedSizeList<Card> CardList { get; set; } 看起来像这样 class FixedSizeList<T> { public FixedSizeList(Int32 size) { this.Size = size; this._Array = new T[size]; } } 类
public new FixedSizeList<Card> CardList { get; set; }
看起来像这样
class FixedSizeList<T>
{
public FixedSizeList(Int32 size)
{
this.Size = size;
this._Array = new T[size];
}
}
类固定大小列表
{
公共固定大小列表(Int32大小)
{
这个。大小=大小;
这个。_数组=新的T[大小];
}
}
现在我想使用这个对象作为另一个类的属性
public FixedSizeList<Card> CardList { get; set; }
public FixedSizeList卡片列表{get;set;}
我注意到我可以用构造函数声明属性
public new FixedSizeList<Card> CardList { get; set; }
public new FixedSizeList CardList{get;set;}
但问题是FixedSizeList没有实例化(我想原因很明显)
那么,我不应该为这段代码得到编译时错误(比如“没有为对象声明的无参数构造函数”),或者实际上可以在属性中声明参数吗
有人能解释一下发生了什么,以及是否有办法解决这个问题吗?(显然,我可以在第二个对象的构造函数中完成这一切,但我正在尝试研究其他技术).将
new
放在属性前面不会导致在初始化时神奇地调用属性的setter并传递该类型的新实例(对于一个小小的关键字来说,这将是一个相当大的负担!)
相反,它已经习惯了
如果希望属性立即返回新实例,则需要为其提供一个已初始化的支持:
public FixedSizeList<Card> CardList
{
get { return _cardList; }
set { _cardList = value; }
}
private FixedSizeList<Card> _cardList = new FixedSizeList<Card>(99999999);
public FixedSizeList卡片列表
{
获取{return\u cardList;}
设置{u cardList=value;}
}
private FixedSizeList _cardList=新的FixedSizeList(9999999);
你想做的是一个工厂
您需要一个静态方法,该方法将在类中返回对象的实例
public static FixedListSize GetInstance() {
return new FixedListSize();
}
我不记得了,如果你必须把这个类标记为static,我想你可能必须这样做。现在我想不通了:\那么你是说C中的新关键字在这个上下文中更像是一个阴影?@Maxim不完全一样,但很相似是的。哇,VB和C真的是两种不同的动物。。。谢谢你的帮助!