Visual Basic 关键字的 C# 等效项:“With” ...“结束于”?

发布于 2024-10-02 06:53:49 字数 527 浏览 1 评论 0原文

在 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

我知道 C# 在创建新对象时可以做到这一点:

Object myObject = new Object { property1 = something, property2 = something2, ...};

但是我该怎么做如果 myOject 已经创建(就像 Visual Basic 所做的那样)?

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

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

// ' You can write:

with myObject
   .property1 = something
   .property2 = something2
   ...
End With

I know C# can do it when creating a new object:

Object myObject = new Object { property1 = something, property2 = something2, ...};

But how do I do that if myOject is already created (like what Visual Basic is doing)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

审判长 2024-10-09 06:53:50

您无法在 C# 中执行此操作。

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

You cannot do this in C#.

This feature is specific to VB and the closest you can come in C# is the object initializer like you describe.

蓝眼睛不忧郁 2024-10-09 06:53:50

这个怎么样?

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;
        });
    }
}

How about this?

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;
        });
    }
}
青巷忧颜 2024-10-09 06:53:50

如果您想避免大量输入,您可以为对象指定一个较短的名称:

var x = myObject;
x.property1 = something;
x.property2 = something2;

If you're trying to avoid lots of typing you can give your object a shorter name:

var x = myObject;
x.property1 = something;
x.property2 = something2;
等你爱我 2024-10-09 06:53:50

为什么 C# 没有 VB.NET 的“with”运算符?

许多人,包括 C# 语言设计者,都认为“with”常常会损害可读性,并且更多的是诅咒而不是祝福。与使用具有某种隐式上下文的块相比,使用有意义的名称声明局部变量并使用该变量对单个对象执行多个操作更清晰。

作者:@Jon Skeet

Why doesn't C# have VB.NET's 'with' operator?

Many people, including the C# language designers, believe that 'with' often harms readability, and is more of a curse than a blessing. It is clearer to declare a local variable with a meaningful name, and use that variable to perform multiple operations on a single object, than it is to have a block with a sort of implicit context.

by @Jon Skeet

红ご颜醉 2024-10-09 06:53:50

@Mark Byers 答案 很好,但变量 x 将在设置属性后生效。并且您不能再次使用名称 x (在同一块中)。

试试这个(并且此示例中的对象必须是引用类型):

void Main()
{
    var myObject1 = new Foo();
    var myObject2 = new Hoo();

    //elided...

    {
        var _ = myObject1;
        _.MyPropertyA = 2;
        _.MyPropertyB = "3";
    }

    {
        var _ = myObject2;
        _.MyPropertyX = 5;
        _.MyPropertyY = "asd";
    }
}

@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";
    }
}
-残月青衣踏尘吟 2024-10-09 06:53:50

为了向后兼容,VB.NET 包含了 VB6 的一些设计缺陷。虽然 Javascript 具有相同的设计缺陷(实际上是一个更糟糕的缺陷,因为它的 with 会导致更加模糊的构造),但大多数其他 C 语法语言没有,因此添加它到 C#。

VB.NET includes some of VB6's design flaws for the sake of backward compatibility. While Javascript has the same design flaw (indeed an even worse one, as its with leads to more ambiguous constructs), most other C-syntax languages don't, so there's no backward-compatibility benefit in adding it to C#.

李不 2024-10-09 06:53:50

如果“with”表达式是类类型,则“With”语句相当于创建该类型的新临时变量,初始化为“With”表达式,并在每个前导“.”之前。与该变量。然而,如果它是一个结构类型,事情就更复杂了。考虑一下代码(显然不是人们通常编写代码的方式,而是为了表达一个观点而编写的:

  With MyPoints(N) ' Array of Point
    N=SomeNewValue
    .X = MyPoints(N).X
    .Y = MyPoints(N).Y
  End With

“With”语句有效地锁存了对 MyPoints(N) 的引用。即使 MyPoints 更改为其他数组,或者N 更改后,锁存的引用仍将指向执行 With 语句时相同的数组元素,如果声明了 Point 类型的局部变量 P 并获取 MyPoints(N),然后写入 PX。和 PY 中,写入只会命中本地副本 P,而不是更新数组 要在 C# 中实现类似的语义,必须使用本地变量来保存 MyPoints 和 N,或者放置 With 语句的内容。在具有 Point 类型的 ref 参数的匿名函数中,为了避免在运行时创建闭包,匿名函数还应该接受(可能是通过引用)来自外部作用域的任何局部变量。

If the "with" expression is a class type, the "With" statement is equivalent to creating a new temporary variable of that type, initialized to the "With" expression, and preceding each leading "." with that variable. If it is a structure type, however, things are more complicated. Consider the code (obviously not the way one would normally write something, but written as it is to make a point:

  With MyPoints(N) ' Array of Point
    N=SomeNewValue
    .X = MyPoints(N).X
    .Y = MyPoints(N).Y
  End With

The "With" statement effectively latches a reference to MyPoints(N). Even if MyPoints is changed to some other array, or N is changed, the latched reference will still point to the same element of the same array as it did when the With statement was executed. If one declared a local variable P of type Point and grabbed MyPoints(N), and then write to P.X and P.Y, the writes would only hit the local copy P, rather than updating the array. To achieve similar semantics in C#, one would have to either use local variables to hold both MyPoints and N, or else place the contents of the With statement within an anonymous function which has a ref parameter of type Point. To avoid having to create a closure at run-time, the anonymous function should also accept, probably by reference, any local variables it will need from the outer scope.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文