简体   繁体   English

在 c# 中是否有与 Delphi 的“with”命令等价的命令?

[英]Is there an equivalent for Delphi's "with" command in c#?

I was wondering if there is a command in C# which I can use like with command in Delphi?我想知道 C# 中是否有一个命令,我可以像 Delphi 中的with command一样使用它吗?

// like this :
with(textbox1)
{
   .text="some text as text of text box";
   .tag=1231;
}

// in Delphi // 在 Delphi

with edit1 do 
 begin
   text="some text as text of edit1";
   tag=1231;
 end;

Not for already created instances.不适用于已创建的实例。

However, when you create a new instance you can do:但是,当您创建一个新实例时,您可以执行以下操作:

var textbox1 = 
   new Textbox
   {
       Text = "some text as text of text box",
       Tag = 1231
   };

No, that does not exist in C#.不,这在 C# 中不存在。

No, it does not exist in C#, however, when creating an object, you can do like this:不,它在 C# 中不存在,但是,在创建object 时,您可以这样做:

var textbox1 = new TextBox {
    Text = "some text as text of text box";
    Tag = 1231
};

It's been 11 years.已经11年了。

C# has added the records feature. C# 增加了记录功能。 You can use the with keyword with c# records.您可以将with关键字与 c# 记录一起使用。

Since records are immutable it instantiates and returns a new object when you use with .由于记录是不可变的,因此当您使用with时,它会实例化并返回一个新的 object。

public record FullName(string FirstName
                     , string LastName);

var name = new FullName("Jack", "Beyer");

var newName = name with { FisrtName = "Mohsen" };

No but depending on what you are trying to do, the following would work:不,但取决于您要执行的操作,以下方法将起作用:

TextBox t = textbox1;

t.text="some text as text of text box";
t.tag=1231;

There's something called using , but compared to Delphi/Pascal it's works more like try/finally.有一种叫做using的东西,但与 Delphi/Pascal 相比,它的工作方式更像 try/finally。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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