【发布时间】:2014-10-25 11:46:38
【问题描述】:
我有通用列表:
class BooksRegister <T>
{
private T[] Register;
public int Count { get; set; }
public BooksRegister()
{
Register = new T[100];
Count = 0;
}
public void Add(T value)
{
if (Count >= 100)
{
return;
}
Register[Count] = value;
Count ++;
}
}
然后是对象类:
class Book
{
public String Author { get; set; }
public String Title { get; set; }
public int Quantity { get; set; }
public Book(String aut, String pav, int kiek)
{
this.Author = aut;
this.Title = pav;
this.Quantity = kiek;
}
public override string ToString()
{
return Author + " \"" + Title + "\" " + Quantity;
}
}
然后是我的Data 课程,我正在从文件中读取信息。我需要实现lazy initialization of object,但是当我这样做时,我无法将我的对象存储在 List 中。
public static void ReadBooks(BooksRegister<Book> allBooks)
{
StreamReader sr = new StreamReader("ListOfBooks.txt");
string line = "";
while ((line = sr.ReadLine()) != null)
{
string[] words = line.Split('|');
String tempAuthor = words[0];
String tempTitle = words[1];
int quant = Convert.ToInt32(words[2]);
Lazy<Book> tempas = new Lazy<Book>();
tempas.Value.Author = tempAuthor;
tempas.Value.Title = tempTitle;
tempas.Value.Quantity = quant;
allBooks.Add(tempas); // error here
}
我该如何解决这个问题?我必须使用延迟初始化必要
【问题讨论】:
-
你试过“allBooks.Add(tempas.Value)”吗?
-
不,那行得通。但是现在我得到 Missing member exception: The lazily-initialized type does not have a public, parameterless constructor.
-
当你立即通过最后一行的 tampas.Value 请求新创建对象的值时,有什么懒惰的?
-
@OndrejJanacek 我是惰性对象初始化的新手,但我必须在我的项目中使用此功能。我正在寻找我能做到最好的方式
标签: c# generics lazy-loading lazy-evaluation lazy-initialization