可能比你想的多:C#中冒号的用法

今天review同事代码时竟然发现C#代码中有类似ObjC的在调用函数时指定形参的调用方式:
function declaration:
void func(string paramString, int paramInt, bool paramBoolean)

Call function:
func(paramString: “Hello World”, paramInt : 99, paramBoolean: true);

之前很少这样写,所以第一次看见时觉得挺奇怪的。
搜索了之后,在Stackoverflow上有热心网友总结了:

Separating a class name from its base class / interface implementations in class definitions

public class Foo : Bar { }
Specifying a generic type constraint on a generic class or method

public class Foo<T> where T : Bar { }

public void Foo<T>() where T : Bar { }
Indicating how to call another constructor on the current class or a base class's constructor prior to the current constructor

public Foo() : base() { }

public Foo(int bar) : this() { }
Specifying the global namespace (as C. Lang points out, this is the namespace alias qualifier)

global::System.Console
Specifying attribute targets

[assembly: AssemblyVersion("1.0.0.0")]
Specifying parameter names

Console.WriteLine(value: "Foo");
As part of a ternary expression

var result = foo ? bar : baz;
As part of a case or goto label

switch(foo) { case bar: break; }

goto Bar;
Foo: return true;
Bar: return false;
Since C# 6, for formatting in interpolated strings

Console.WriteLine($"{DateTime.Now:yyyyMMdd}");
Since C# 7, in tuple element names

var foo = (bar: "a", baz: "b");
Console.WriteLine(foo.bar);

 

打赏

沪公网安备 31011302002866号