开发者

About the usage of lazy feature in C# 4.0

开发者 https://www.devze.com 2023-03-19 20:01 出处:网络
I have a Userdetails class like the one below public class UserDetails { public string ssn; public string username;

I have a Userdetails class like the one below

public class UserDetails
{
    public string ssn;

    public string username;

    public string ema开发者_开发知识库ilid;

    public Address address;
}

Here Address is another class that will have public fields like

public class Address
{
    public int id;

    public string address;
}

Now, when the user logs in the app, i construct the Userdetails object. Now i will not use address object inside the userdetails very frequently, but have got data.

In this scenario how can i use the Lazy initialization feature of C# 4.0.

Note that the data is taken from direct db query and none of these classes have constructors or other means to get the data. These are just representations of the database fields in C#.

Suggest me the best way to use lazy initialization here.


You can have a private lazy address:

private Lazy<Address> _address = new Lazy<Address>(() => {
    ---code to get the address---
});

public Address address {
    get {
        return _address.Value;
    }    
}
0

精彩评论

暂无评论...
验证码 换一张
取 消