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正在做什么),我该怎么做?
这个怎么样?
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)
| 归档时间: |
|
| 查看次数: |
6960 次 |
| 最近记录: |