C# equivalent for Visual Basic keyword: 'With' … 'End With'?

后端 未结 7 1957
南笙
南笙 2020-12-11 04:21

In Visual Basic, if you are going to change multiple properties of a single object, there\'s a With/End With statement:

Dim myObject as Object

         


        
7条回答
  •  Happy的楠姐
    2020-12-11 04:41

    How about this?

    static class Extension
    {
        public static void With(this T obj, Action a)
        {
            a(obj);
        }    
    }
    
    class Program
    {
        class Obj
        {
            public int Prop1 { get; set; }
            public int Prop2 { get; set; }
            public int Prop3 { get; set; }
            public int Prop4 { get; set; }
        }
    
        static void Main(string[] args)
        {
            var detailedName = new Obj();
            detailedName.With(o => {
                o.Prop1 = 1;
                o.Prop2 = 2;
                o.Prop3 = 3;
                o.Prop4 = 4;
            });
        }
    }
    

提交回复
热议问题