我知道VB.Net并且正在尝试刷新我的C#。 C#中有一个With块等价物吗?
由于
答案 0 :(得分:51)
虽然C#与一般情况没有任何直接等价,但C#3获取构造函数调用的对象初始化语法:
var foo = new Foo { Property1 = value1, Property2 = value2, etc };
有关详细信息,请参阅深度C#的第8章 - 您可以从Manning's web site免费下载。
(免责声明 - 是的,将这本书交到更多人的手中符合我的利益。但是,嘿,这是一个免费章节,可以为您提供有关相关主题的更多信息......)
答案 1 :(得分:22)
这就是Visual C#项目经理所说的: Why doesn't C# have a 'with' statement?
很多人,包括C#语言设计师,都认为'有' 经常损害可读性,更多的是诅咒而不是祝福。它是 更清楚地声明具有有意义名称的局部变量,并使用 该变量对单个对象执行多个操作比 它是一个具有某种隐式上下文的块。
答案 2 :(得分:21)
正如上面链接的Visual C#程序管理器所说,在有些情况下,With语句更有效,这是他用作重复访问复杂表达式的简写时给出的示例。
使用扩展方法和泛型,你可以创建一些与With语句模糊等价的东西,添加如下内容:
public static T With<T>(this T item, Action<T> action)
{
action(item);
return item;
}
举一个如何使用它的简单例子,使用lambda语法然后你可以用它来改变这样的东西:
updateRoleFamily.RoleFamilyDescription = roleFamilyDescription;
updateRoleFamily.RoleFamilyCode = roleFamilyCode;
对此:
updateRoleFamily.With(rf =>
{
rf.RoleFamilyDescription = roleFamilyDescription;
rf.RoleFamilyCode = roleFamilyCode;
});
在这样的示例中,唯一的优势可能是更好的布局,但是通过更复杂的引用和更多属性,它可以为您提供更易读的代码。
答案 3 :(得分:12)
不,没有。
答案 4 :(得分:11)
在“Using Objects”部分的页面下方大约3/4:
VB:
With hero
.Name = "SpamMan"
.PowerLevel = 3
End With
C#:
//No "With" construct
hero.Name = "SpamMan";
hero.PowerLevel = 3;
答案 5 :(得分:4)
答案 6 :(得分:2)
在C#版本9中引入了with
键盘!
您可以使用它来创建对象的副本,如下所示
Person brother = person with { FirstName = "Paul" };
“上面的行创建了一个新的Person记录,其中LastName属性是person的副本,而FirstName是” Paul“。您可以在with-expression中设置任意数量的属性。 “ clone”方法可能由您编写。如果记录类型的方法与任何合成方法的签名都匹配,则编译器不会合成该方法。”
更新:
在编写此答案时,C#9尚未正式发布,而仅在预览版中。但是,planned将于2020年11月与.NET 5.0一起发布
有关更多信息,请检查record types。
答案 7 :(得分:2)
我所做的是使用csharp ref关键字。例如:
ref MySubClassType e = ref MyMainClass.MySubClass;
然后您可以使用以下快捷方式:
e.property
代替MyMainClass.MySubClass.property
答案 8 :(得分:2)
最简单的语法是:
{
var where = new MyObject();
where.property = "xxx";
where.SomeFunction("yyy");
}
{
var where = new MyObject();
where.property = "zzz";
where.SomeFunction("uuu");
}
如果你想重用变量名,实际上这样的额外代码块非常方便。
答案 9 :(得分:1)
我是这样用的:
worksheet.get_Range(11, 1, 11, 41)
.SetHeadFontStyle()
.SetHeadFillStyle(45)
.SetBorders(
XlBorderWeight.xlMedium
, XlBorderWeight.xlThick
, XlBorderWeight.xlMedium
, XlBorderWeight.xlThick)
;
SetHeadFontStyle / SetHeadFillStyle是范围的ExtMethod,如下所示:
public static Range SetHeadFillStyle(this Range rng, int colorIndex)
{
//do some operation
return rng;
}
执行一些操作并返回范围以进行下一步操作
看起来像Linq:)
但现在仍然不能完全看起来像 - 有价值的设定值
with cell.Border(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
答案 10 :(得分:1)
有时您可以通过以下方式逃脱:
var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(Color.Gray);
fill.PatternColor = Color.Black;
fill.Gradient = ...
(EPPLus @ http://zeeshanumardotnet.blogspot.com的代码示例)
答案 11 :(得分:1)
这里With
的忠实粉丝!
这实际上是我当前的C#代码:
if (SKYLib.AccountsPayable.Client.ApiAuthorization.Authorization.AccessTokenExpiry == null || SKYLib.AccountsPayable.Client.ApiAuthorization.Authorization.AccessTokenExpiry < DateTime.Now)
{
SKYLib.AccountsPayable.Client.ApiAuthorization.Authorization.Refresh();
_api = new SKYLib.AccountsPayable.Api.DefaultApi(new SKYLib.AccountsPayable.Client.Configuration { DefaultHeader = SKYLib.AccountsPayable.Client.ApiAuthorization.Authorization.ApiHeader });
}
在VB中可能是:
With SKYLib.AccountsPayable.Client.ApiAuthorization.Authorization
If .AccessTokenExpiry Is Nothing OrElse .AccessTokenExpiry < Now Then .Refresh()
_api = New SKYLib.AccountsPayable.Api.DefaultApi(New SKYLib.AccountsPayable.Client.Configuration With {DefaultHeader = .ApiHeaders}
End With
我想清楚得多。您甚至可以通过调整With
变量来使其更简洁。而且,就风格而言,我还有一个 choice !也许是C#程序管理器忽略了的东西。
顺便说一句,看到这种情况不是很常见,但是我偶尔使用它:
代替
Using oClient As HttpClient = New HttpClient
With oClient
.BaseAddress = New Uri("http://mysite")
.Timeout = New TimeSpan(123)
.PostAsync( ... )
End With
End Using
您可以使用
With New HttpClient
.BaseAddress = New Uri("http://mysite")
.Timeout = New TimeSpan(123)
.PostAsync( ... )
End With
您冒着拍手的风险-我也要张贴! -但似乎您可以在处置等方面获得Using
语句的所有好处,而无需额外的固定条件。
注意:这有时可能会出错,因此仅将其用于非关键代码。还是根本没有。记住:您可以选择...
答案 12 :(得分:1)
要使生活更轻松一点,您可以使用垂直选择快速编辑内容
http://joelabrahamsson.com/select-columns-of-text-in-visual-studio/
答案 13 :(得分:0)
我认为“ with”的衣橱是static using
,但仅适用于static的方法或属性。
例如
using static System.Math;
...
public double Area
{
get { return PI * Pow(Radius, 2); } // PI == System.Math.PI
}
更多信息: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-static
答案 14 :(得分:0)
对我来说,我试图自动生成代码,并且需要为多个不同的类重用一个简单的变量,如“ x”,这样我就不必继续生成新的变量名。我发现,只要将代码放在花括号部分{}中,就可以限制变量的范围并多次重复使用。
查看示例:
public class Main
{
public void Execute()
{
// Execute new Foos and new Bars many times with same variable.
double a = 0;
double b = 0;
double c = 0;
double d = 0;
double e = 0;
double f = 0;
double length = 0;
double area = 0;
double size = 0;
{
Foo x = new Foo(5, 6).Execute();
a = x.A;
b = x.B;
c = x.C;
d = x.D;
e = x.E;
f = x.F;
}
{
Bar x = new Bar("red", "circle").Execute();
length = x.Length;
area = x.Area;
size = x.Size;
}
{
Foo x = new Foo(3, 10).Execute();
a = x.A;
b = x.B;
c = x.C;
d = x.D;
e = x.E;
f = x.F;
}
{
Bar x = new Bar("blue", "square").Execute();
length = x.Length;
area = x.Area;
size = x.Size;
}
}
}
public class Foo
{
public int X { get; set; }
public int Y { get; set; }
public double A { get; private set; }
public double B { get; private set; }
public double C { get; private set; }
public double D { get; private set; }
public double E { get; private set; }
public double F { get; private set; }
public Foo(int x, int y)
{
X = x;
Y = y;
}
public Foo Execute()
{
A = X * Y;
B = X + Y;
C = X / (X + Y + 1);
D = Y / (X + Y + 1);
E = (X + Y) / (X + Y + 1);
F = (Y - X) / (X + Y + 1);
return this;
}
}
public class Bar
{
public string Color { get; set; }
public string Shape { get; set; }
public double Size { get; private set; }
public double Area { get; private set; }
public double Length { get; private set; }
public Bar(string color, string shape)
{
Color = color;
Shape = shape;
}
public Bar Execute()
{
Length = Color.Length + Shape.Length;
Area = Color.Length * Shape.Length;
Size = Area * Length;
return this;
}
}
在VB中,我将完全使用With而不需要变量“ x”。不包括Foo和Bar的vb类定义,该vb代码为:
Public Class Main
Public Sub Execute()
Dim a As Double = 0
Dim b As Double = 0
Dim c As Double = 0
Dim d As Double = 0
Dim e As Double = 0
Dim f As Double = 0
Dim length As Double = 0
Dim area As Double = 0
Dim size As Double = 0
With New Foo(5, 6).Execute()
a = .A
b = .B
c = .C
d = .D
e = .E
f = .F
End With
With New Bar("red", "circle").Execute()
length = .Length
area = .Area
size = .Size
End With
With New Foo(3, 10).Execute()
a = .A
b = .B
c = .C
d = .D
e = .E
f = .F
End With
With New Bar("blue", "square").Execute()
length = .Length
area = .Area
size = .Size
End With
End Sub
End Class
答案 15 :(得分:-1)
还有一个有趣的实现with-pattern
public static T With<T>(this T o, params object[] pattern) => o;
public static T To<T>(this T o, out T x) => x = o;
您可以按the link浏览更多详情并研究online code samples。
使用变化
static Point Sample0() => new Point().To(out var p).With(
p.X = 123,
p.Y = 321,
p.Name = "abc"
);
public static Point GetPoint() => new Point { Name = "Point Name" };
static string NameProperty { get; set; }
static string NameField;
static void Sample1()
{
string nameLocal;
GetPoint().To(out var p).With(
p.X = 123,
p.Y = 321,
p.Name.To(out var name), /* right side assignment to the new variable */
p.Name.To(out nameLocal), /* right side assignment to the declared var */
NameField = p.Name, /* left side assignment to the declared variable */
NameProperty = p.Name /* left side assignment to the property */
);
Console.WriteLine(name);
Console.WriteLine(nameLocal);
Console.WriteLine(NameField);
Console.WriteLine(NameProperty);
}
static void Sample2() /* non-null propogation sample */
{
((Point)null).To(out var p)?.With(
p.X = 123,
p.Y = 321,
p.Name.To(out var name)
);
Console.WriteLine("No exception");
}
static void Sample3() /* recursion */
{
GetPerson().To(out var p).With(
p.Name.To(out var name),
p.Subperson.To(out var p0).With(
p0.Name.To(out var subpersonName0)
),
p.GetSubperson().To(out var p1).With( /* method return */
p1.Name.To(out var subpersonName1)
)
);
Console.WriteLine(subpersonName0);
Console.WriteLine(subpersonName1);
}
如果使用结构[值类型],类似的扩展方法也很有用
public static TR Let<T, TR>(this T o, TR y) => y;
可以在With方法之后应用,因为默认情况下将返回未修改的struct
副本struct Point
{
public double X;
public double Y;
public string Name;
}
static Point Sample0() => new Point().To(out var p).With(
p.X = 123,
p.Y = 321,
p.Name = "abc"
).Let(p);
如果你愿意,尽情享受!
答案 16 :(得分:-3)
如果有多个级别的对象,您可以使用“using”指令获得类似的功能:
using System;
using GenderType = Hero.GenderType; //This is the shorthand using directive
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var myHero = new Hero();
myHero.Name = "SpamMan";
myHero.PowerLevel = 3;
myHero.Gender = GenderType.Male; //instead of myHero.Gender = Hero.GenderType.Male;
}
}
public class Hero
{
public enum GenderType
{
Male,
Female,
Other
}
public string Name;
public int PowerLevel;
public GenderType Gender;
}
答案 17 :(得分:-4)
HMM。我从来没有在任何深度使用过VB.net,所以我在这里做了一个假设,但我认为'使用'块可能接近你想要的。
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
var yourVariable = new yourObject { param1 = 20, param2 = "some string" };