简体   繁体   中英

How can I convert the instantiation of an object to a lambda expression

Excuse me, is it possible to convert that code to lambda expression

var person = new Person();
person.Age = 17;
person.FirstName = "Todor";
person.SecondName = "Todorov";

it's quite useless but yes:

Func<Person> person = () =>
{
    return new Person()
    {
        Age = 17,
        FirstName = "Todor",
        SecondName = "Todorov"
    }
};

This approach will create some sort of a readonly variable, because every time that you call it you will get a new instance with the hard coded values.

Another approach could be to make a generator function:

Func<int, string, string, Person> generatePerson = (int a, string f, string s) =>   
{
    return new Person()
    {
        Age = a,
        FirstName = f,
        SecondName = s
    };
};

This is like an external constructor that will generate you different objects which you can parametrize

var person = generatePerson(17, "Todor", "Todorov");

You can also skip the declaration of the input types:

Func<int, string, string, Person> generatePerson = (a, f, s) =>....

I did it for clarity reasons above.

one of the short thing you can do is

new Person(){
Age = 17,
FirstName = "Todor",
SecondName = "Todorov"
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM