C# 中缺少“with”关键字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/601153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:51:31  来源:igfitidea点击:

Missing the 'with' keyword in C#

c#.netsyntaxkeyword

提问by Matt Davis

I was looking at the online help for the Infragistics control library today and saw some VB code that used the Withkeyword to set multiple properties on a tab control. It's been nearly 10 years since I've done any VB programming, and I had all but forgotten that this keyword even existed. Since I'm still relatively new to C#, I quickly went to see if it had a similar construct. Sadly, I haven't been able to find anything.

我今天正在查看 Infragistics 控件库的在线帮助,看到一些 VB 代码使用With关键字在选项卡控件上设置多个属性。我已经将近 10 年没有做任何 VB 编程了,我几乎忘记了这个关键字甚至存在。由于我对 C# 还是比较陌生,我很快就去看看它是否有类似的结构。可悲的是,我一直找不到任何东西。

Does C# have a keyword or similar construct to mimic the functionality provided by the Withkeyword in VB? If not, is there a technical reason why C# does not have this?

C# 是否有一个关键字或类似的结构来模仿VB 中With关键字提供的功能?如果没有,是否有技术原因 C# 没有这个?

EDIT:I searched for an existing entry on this before asking my question, but didn't find the one Ray referred to (here). To refine the question, then, is there a technical reason why C# does not have this? And Gulzar nailed it - no, there are not a technical reason why C# does not have a Withkeyword. It was a design decision by the language designers.

编辑:在问我的问题之前,我搜索了一个现有的条目,但没有找到 Ray 提到的那个(这里)。那么,为了细化这个问题,C# 没有这个有技术原因吗?Gulzar 指出了这一点 - 不,C# 没有With关键字没有技术原因。这是语言设计者的设计决定。

采纳答案by Gulzar Nazim

This is what C# program manager has to say: Why doesn't C# have a 'with' statement?

这就是 C# 程序管理器必须说的: 为什么 C# 没有“with”语句?

  • Small or non-existent readability benefits.We thought the readability benefits were small or non-existent. I won't go as far as to say that the with statement makes code less readable, but some people probably would.

  • Increased language complexity.Adding a with statement would make the language more complex. For example, VB had to add new language syntax to address the potential ambiguity between a local variable (Text) and a property on the "with" target (.Text). Other ways of solving this problem also introduce language complexity. Another approach is to push a scope and make the property hide the local variable, but then there's no way to refer to the local without adding some escape syntax.

  • C++ heritage.C++ has never had a with statement, and the lack of such a statement is not generally thought to be a problem by C++ developers. Also, we didn't feel that other changes -- changes in the kind of code people are writing, changes in the platform, other changes in the language, etc. -- made with statements more necessary.

  • 小的或不存在的可读性优势。我们认为可读性的好处很小或根本不存在。我不会说 with 语句会降低代码的可读性,但有些人可能会。

  • 增加语言复杂度。添加 with 语句会使语言更加复杂。例如,VB 必须添加新的语言语法来解决局部变量 (Text) 和“with”目标 (.Text) 上的属性之间潜在的歧义。解决此问题的其他方法也引入了语言复杂性。另一种方法是推送一个范围并使属性隐藏局部变量,但是如果不添加一些转义语法,就无法引用局部变量。

  • C++ 遗产。C++ 从来没有 with 语句,缺少这样的语句一般不会被 C++ 开发人员认为是一个问题。此外,我们并不觉得其他变化——人们正在编写的代码类型的变化、平台的变化、语言的其他变化等——更需要声明。

回答by Ed S.

No, it was a conscious decision made by the C# dev team. People have mixed feelings about the 'with' keyword because it can degrade code readability if abused (nesting with's).

不,这是 C# 开发团队有意识地做出的决定。人们对“with”关键字有复杂的感觉,因为如果滥用(嵌套 with )会降低代码的可读性。

回答by Kibbee

I don't imagine that there's a technical reason it doesn't exist. What I would say though, is that the reason that it doesn't exist is that it's a programming construct that exists solely for the purpose of cutting down on typing. With things like intellisense, and copy and paste, the world doesn't really have much demand for features like this anymore. I use VB.Net, and can't recall if it's even still supported. Never really felt the need to use it.

我不认为它不存在有技术原因。不过我要说的是,它不存在的原因是它是一种编程结构,其存在的目的仅仅是为了减少打字。有了智能感知、复制和粘贴等功能,世界对此类功能的需求就不再那么大了。我使用 VB.Net,不记得它是否仍然受支持。从来没有真正觉得需要使用它。

回答by Matthew Olenik

In C# 3.0, you can use object initializers to achieve a similar effect when creating objects.

在 C# 3.0 中,您可以在创建对象时使用对象初始值设定项来实现类似的效果。

var control = new MyControl
{
    Title = "title",
    SomeEvent += handler,
    SomeProperty = foo,
    Another = bar
};

Rather than:

而不是:

var control = new MyControl();
control.Title = "title";
control.SomeEvent += handler;
control.SomeProperty = foo;
control.Another = bar;

Note that, although this syntax was introduced in C# 3.0, you can still use it with the 2.0 framework, it's just syntactic sugar introduced by the compiler.

请注意,虽然此语法是在 C# 3.0 中引入的,但您仍然可以在 2.0 框架中使用它,这只是编译器引入的语法糖。

回答by Guffa

No, the "with" keyword was intentionally left out of the language.

不,“with”关键字被故意排除在语言之外。

If you have a lengthy name of reference, you can easily make a shorter reference to it using a variable, and even give it a limited scope:

如果您有一个很长的引用名称,您可以使用变量轻松地对其进行更短的引用,甚至可以给它一个有限的范围:

{
   SomeClass r = Some.Lengthy.Path.To.Get.To.A.Referece;
   r.Some = 42;
   r.Properites = "none";
   r.To = 1;
   r.Set = null;
}

回答by Gabe Moothart

It is not idiomatic c#, but if you really want a withequivalent, you could do this:

它不是惯用的 c#,但如果你真的想要一个with等价物,你可以这样做:

Person MyPersonWithALongName = new Person();
MyUtils.With(MyPersonWithALongName, p => {

    p.Name = "George";
    p.Address = "123 Main St";
    ...

});

class MyUtils {

    public static void With<T>(T x, Action<T> do) {
        do(x);
    }
}

Update:
It occurred to me that you could trivially make this more concise by turning it into an extension method, perhaps renaming it "Alias" or "As" for reabability:

更新:
我想到您可以通过将其转换为扩展方法来简单地使其更简洁,也许将其重命名为“别名”或“作为”以提高可行性:

MyPersonWithALongName.Alias(p => {
    p.Name = "George";
    p.Address = "123 Main St";
    ...
});

回答by sonjz

For these solutions:

对于这些解决方案:

// ....
// (class Common)

public static void With<T>(T property, Action<T> action) {
    action(property);
}

// ...
// usage somewhere ...    
Person person = GetPerson();
Common.With(person, p => { p.Name = "test", p.Age = "123" });

It just seems we are aliasing the variable with "p". As solutions go, I found it easy enough to keep the variable name short, this sort of solution with a "With" generic doesn't buy any elegance.

似乎我们用“p”为变量设置了别名。随着解决方案的发展,我发现保持变量名简短很容易,这种带有“With”泛型的解决方案并不优雅。

Ideally, we'd all like to see some reworking of the syntax so the usage is similar to how initialization of multiple properties works today:

理想情况下,我们都希望看到对语法进行一些修改,因此其用法类似于当今多个属性的初始化工作方式:

Person person = new Person() { Name = "test", Age = "123" };