Visual Basic关键字的C#等价物:'With'...'End With'?

Xaq*_*ron 8 c# vb.net language-design with-statement

在Visual Basic中,如果要更改单个对象的多个属性,则需要With/End With声明:

Dim myObject as Object

// ' Rather than writing:
myObject.property1 = something
myObject.property2 = something2

// ' You can write:

with myObject
   .property1 = something
   .property2 = something2
   ...
End With
Run Code Online (Sandbox Code Playgroud)

我知道C#可以在创建新对象时执行此操作:

Object myObject = new Object { property1 = something, property2 = something2, ...};
Run Code Online (Sandbox Code Playgroud)

但是,如果myOject已经创建(如Visual Basic正在做什么),我该怎么做?

Pie*_*kel 11

你不能在C#中做到这一点.

此功能特定于VB,您可以使用C#最接近的是您描述的对象初始值设定项.


Cha*_*ion 6

这个怎么样?

static class Extension
{
    public static void With<T>(this T obj, Action<T> 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;
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一下.创意+1 :-) (2认同)