简体   繁体   English

如何将对象的实例化为lambda表达式

[英]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 请问,有可能将该代码转换为lambda表达式吗?

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"
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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