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

后端 未结 7 1973
南笙
南笙 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条回答
  •  星月不相逢
    2020-12-11 04:47

    @Mark Byers answer is good but the variable x will live after properties are set. And you can't use name x again (in same block).

    Try this (And object must be reference type in this sample) :

    void Main()
    {
        var myObject1 = new Foo();
        var myObject2 = new Hoo();
    
        //elided...
    
        {
            var _ = myObject1;
            _.MyPropertyA = 2;
            _.MyPropertyB = "3";
        }
    
        {
            var _ = myObject2;
            _.MyPropertyX = 5;
            _.MyPropertyY = "asd";
        }
    }
    

提交回复
热议问题