简体   繁体   中英

Is there a way in C# to access object properties in old, Pascal “with” keyword way?

This is the Pascal sample I want to achieve in C#:

With myBook do
 Begin
  Title  := 'Some Book';
  Author := 'Victor John Saliba';
  ISBN   := '0-12-345678-9';
  Price  := 25.5;
 End;

Only when constructing.

var foo = new Foo
{
  Title = "lol",
  Author = "Som Gai",
  ISBWhatever = "111"
}

VB.NET has the 'with' keyword, but c# does not.

Here you can find an explanation here.

Excerpt:

  • 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.

No there is not. It has been discussed before and most people don't want it.

It hurts readability, creates ambiguous situations, makes debugging harder and it's convenience is largely offset by IntelliSense.

To address your last comment, you can of course write:

myBook.Title = "Some Book";
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM