Creating an object that passes a lambda expression to a constructor

I have an object with a number of properties.

I want to be able to assign some of these properties when calling the constructor.

The obvious solution is to either have a constructor that takes a parameter for each of the properties, but it is nasty when there are lots. Another solution would be to create overloads, each of which accepts a subset of the property values, but I could get dozens of overloads.

So, I thought it would be nice if I could say.

MyObject x = new MyObject(o => o.Property1 = "ABC", o.PropertyN = xx, ...);

The problem is that I'm too dull to work , how to do it.

Did you know?

+3
source share
4 answers

# 3 .

:

using System;

class Program
{
    static void Main()
    {
        Foo foo = new Foo { Bar = "bar" };
    }
}

class Foo
{
    public String Bar { get; set; }
}

, , (, <>g__initLocal0). , , .

Main :

static void Main()
{
    // Create an instance of "Foo".
    Foo <>g__initLocal0 = new Foo();
    // Set the property.
    <>g__initLocal0.Bar = "bar";
    // Now create my "Foo" instance and set it
    // equal to the compiler instance which 
    // has the property set.
    Foo foo = <>g__initLocal0;
}
+8

.

, - , , , Action .

public class MyClass
{
    public MyClass(Action<MyClass> populator)
    {
        populator.Invoke(this);
    }

    public int MyInt { get; set; }
    public void DoSomething() 
    {
        Console.WriteLine(this.MyInt);
    }
}

.

var x = new MyClass(mc => { mc.MyInt = 1; mc.DoSomething(); });
+3

, , - (, MyObject) N , Object Initializer # 3.0, N :

MyObject x = new MyObject {Property1 = 5, Property4 = "test", PropertyN = 6.7};

/ ./

+1
source
class MyObject
{
     public MyObject(params Action<MyObject>[]inputs)
     {
          foreach(Action<MyObject> input in inputs)
          {
               input(this);
          }
     }
}

I may have the wrong type of function, but I think this is what you are describing.

0
source

Source: https://habr.com/ru/post/1710150/


All Articles