与 C# 中的块等效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/481725/
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 05:08:32  来源:igfitidea点击:

With block equivalent in C#?

c#.netvb.net

提问by Dan Appleyard

I know VB.Net and am trying to brush up on my C#. Is there a With block equivalent in C#?

我知道 VB.Net 并且正在尝试复习我的 C#。C# 中是否有等价的 With 块?

Thanks

谢谢

回答by Guulh

No, there is not.

不,那里没有。

回答by BBetances

You could use the argument accumulator pattern.

您可以使用参数累加器模式。

Big discussion about this here:

关于这里的大讨论:

http://blogs.msdn.com/csharpfaq/archive/2004/03/11/87817.aspx

http://blogs.msdn.com/csharpfaq/archive/2004/03/11/87817.aspx

回答by mlennox

hmm. I have never used VB.net in any depth, so I'm making an assumption here, but I think the 'using' block might be close to what you want.

唔。我从来没有深入使用过 VB.net,所以我在这里做一个假设,但我认为“使用”块可能接近你想要的。

using defines a block scope for a variable, see the example below

using 定义了一个变量的块作用域,见下面的例子

using ( int temp = someFunction(param1) ) {
   temp++;  // this works fine
}

temp++; // this blows up as temp is out of scope here and has been disposed

Here is an article from Microsoft that explains a bit more

这是微软的一篇文章,解释了更多



EDIT: yeah, this answer is wrong - the original assumption was incorrect. VB's 'WITH' is more like the new C# object initialisers:

编辑:是的,这个答案是错误的 - 最初的假设是错误的。VB 的“WITH”更像是新的 C# 对象初始值设定项:

var yourVariable = new yourObject { param1 = 20, param2 = "some string" };

回答by Timothy Carter

About 3/4 down the page in the "Using Objects" section:

在“使用对象”部分的页面下方约 3/4 :

VB:

VB:

With hero 
  .Name = "SpamMan" 
  .PowerLevel = 3 
End With 

C#:

C#:

//No "With" construct
hero.Name = "SpamMan"; 
hero.PowerLevel = 3; 

回答by Jon Skeet

Although C# doesn't have any direct equivalent for the general case, C# 3 gain object initializer syntax for constructor calls:

尽管 C# 对于一般情况没有任何直接等效项,但 C# 3 为构造函数调用获得了对象初始值设定项语法:

var foo = new Foo { Property1 = value1, Property2 = value2, etc };

See chapter 8 of C# in Depth for more details - you can download it for free from Manning's web site.

有关更多详细信息,请参阅 C# 深入了解的第 8 章 - 您可以从Manning 的网站免费下载。

(Disclaimer - yes, it's in my interest to get the book into more people's hands. But hey, it's a free chapter which gives you more information on a related topic...)

(免责声明 - 是的,让更多人掌握这本书符合我的利益。但是,嘿,这是一个免费章节,可为您提供有关相关主题的更多信息......)

回答by Gulzar Nazim

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

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

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.

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

回答by RTPeat

As the Visual C# Program Manager linked above says, there are limited situations where the With statement is more efficient, the example he gives when it is being used as a shorthand to repeatedly access a complex expression.

正如上面链接的 Visual C# 程序管理器所说,With 语句在有限的情况下效率更高,他给出的示例是当它被用作重复访问复杂表达式的速记时。

Using an extension method and generics you can create something that is vaguely equivalent to a With statement, by adding something like this:

使用扩展方法和泛型,您可以通过添加以下内容来创建与 With 语句大致等效的内容:

    public static T With<T>(this T item, Action<T> action)
    {
        action(item);
        return item;
    }

Taking a simple example of how it could be used, using lambda syntax you can then use it to change something like this:

举一个如何使用它的简单示例,使用 lambda 语法,您可以使用它来更改如下内容:

    updateRoleFamily.RoleFamilyDescription = roleFamilyDescription;
    updateRoleFamily.RoleFamilyCode = roleFamilyCode;

To this:

对此:

    updateRoleFamily.With(rf =>
          {
              rf.RoleFamilyDescription = roleFamilyDescription;
              rf.RoleFamilyCode = roleFamilyCode;
          });

On an example like this, the only advantage is perhaps a nicer layout, but with a more complex reference and more properties, it could well give you more readable code.

在这样的示例中,唯一的优势可能是更好的布局,但是有了更复杂的引用和更多的属性,它可以为您提供更易读的代码。

回答by Sean

Sometimes you can get away with doing the following:

有时,您可以通过执行以下操作来逃脱惩罚:

var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(Color.Gray);
fill.PatternColor = Color.Black;
fill.Gradient = ...

(Code sample for EPPLus @ http://zeeshanumardotnet.blogspot.com)

(EPPLus 的代码示例@ http://zeeshanumardotnet.blogspot.com

回答by IlPADlI

I was using this way:

我是这样使用的:

        worksheet.get_Range(11, 1, 11, 41)
            .SetHeadFontStyle()
            .SetHeadFillStyle(45)
            .SetBorders(
                XlBorderWeight.xlMedium
                , XlBorderWeight.xlThick
                , XlBorderWeight.xlMedium
                , XlBorderWeight.xlThick)
            ;

SetHeadFontStyle / SetHeadFillStyle is ExtMethod of Rangelike below:

SetHeadFontStyle / SetHeadFillStyle 是Range 的ExtMethod,如下所示:

 public static Range SetHeadFillStyle(this Range rng, int colorIndex)
 {
     //do some operation
     return rng;
 }

do some operation and return the Rangefor next operation

做一些操作并返回下一个操作的范围

it's look like Linq :)

它看起来像 Linq :)

but now still can't fully look like it -- propery set value

但现在仍然不能完全像它 - 属性设置值

with cell.Border(xlEdgeTop)
   .LineStyle = xlContinuous
   .Weight = xlMedium
   .ColorIndex = xlAutomatic

回答by Wouter Schut

Most simple syntax would be:

最简单的语法是:

{
    var where = new MyObject();
    where.property = "xxx";
    where.SomeFunction("yyy");
}

{
    var where = new MyObject();
    where.property = "zzz";
    where.SomeFunction("uuu");
}

Actually extra code-blocks like that are very handy if you want to re-use variable names.

实际上,如果您想重用变量名,像这样的额外代码块非常方便。