复制代码 代码如下:
///这行代码表明:要创建一个延迟加载的字符串对象s
///原型为LazyT> 对象名=new LazyT>(FunT>)
///采用泛型委托进行构造,实例化此委托时要求必须是返回值T类型的方法
///如在本例中,T为string,则TestLazy.GetString方法的返回值必须也是string类型
Lazystring> s = new Lazystring>(TestLazy.GetString);
本例中TestLazy.GetString()方法如下示:
public class TestLazy
{
public static string GetString()
{
return DateTime.Now.ToLongTimeString();
}
}
复制代码 代码如下:
class Program
{
static void Main(string[] args)
{
///这行代码表明:要创建一个延迟加载的字符串对象s
///原型为Lazy 对象名=new Lazy(Fun)
///采用泛型委托进行构造,实例化此委托时要求必须是返回值T类型的方法
///如在本例中,T为string,则TestLazy.GetString方法的返回值必须也是string类型
Lazy s = new Lazy(TestLazy.GetString);
Console.WriteLine(s.IsValueCreated);//返回False
Console.WriteLine(s.IsValueCreated);//返回True
}
}
public class TestLazy
{
public static string GetString()
{
return DateTime.Now.ToLongTimeString();
}
}
复制代码 代码如下:
class Program
{
static void Main(string[] args)
{
BlogUser blogUser = new BlogUser(1);
Console.WriteLine("blogUser has been initialized");
{
Console.WriteLine(article.Title);}
}
}
public class BlogUser
{
public int Id { get; private set; }
public Lazy> Articles { get; private set; }
public BlogUser(int id)
{
this.Id = id;
Articles =new Lazy>(()=>ArticleServices.GetArticesByID(id));
Console.WriteLine("BlogUser Initializer");
}
}
public class Article
{
public int Id { get; set; }
public string Title{get;set;}
public DateTime PublishDate { get; set;}
public class ArticleServices
{
public static List GetArticesByID(int blogUserID)
{
List articles = new List {
new Article{Id=1,Title="Lazy Load",PublishDate=DateTime.Parse("2011-4-20")},
new Article{Id=2,Title="Delegate",PublishDate=DateTime.Parse("2011-4-21")},
new Article{Id=3,Title="Event",PublishDate=DateTime.Parse("2011-4-22")},
new Article{Id=4,Title="Thread",PublishDate=DateTime.Parse("2011-4-23}
};
Console.WriteLine("Article Initalizer");
return articles;
}
}
新闻热点
疑难解答
图片精选