1.Optional and Named Parameters
calls these methods can optionally not specify some of the arguments, thereby accepting the default values.
when you call a method, you can specify arguments by using the name of their parameters.
When you pass arguments to a method, the compiler evaluates the arguments from left to right.
示例:
Rules and Guidelines
when defining a method that specifies default values for some of its parameters:
1.can specify default values for the parameters of methods, constructor methods, parameterful properties (C# indexers)
can specify default values for parameters that are part of a delegate definition. Then, when invoking a variable of this delegate type, you can omit the arguments and accept the default values.
2.Parameters with default values must come after any parameters that do not have default values.That is, after you define a parameter as having a default value, then all parameters to the right of it must also have default values.
a params array parameter (discussed later in this chapter) must come after all parameters (including those that have default values), and the array cannot have a default value itself.
For example, in the definition of my M method, I would get a compiler error if I removed the default value ("A") for s.
3.Default values must be constant values known at compile time.
This means that you can set default values for parameters of types that C# considers to be primitive types. This also includes enumerated types, and any reference type can be set to null.
For a parameter of an arbitrary value type,you can set the default value to be an instance of the value type, with all its fields containing zeroes.You can use the default keyword or the new keyword to express this; both syntaxes produce identical Intermediate Language (IL) code.
Examples of both syntaxes are used by my M method for setting the default value for the dt parameter and guid parameter, respectively.
4.Be careful not to rename parameter variables because any callers who are passing arguments by parameter name will have to modify their code.
For example, in the declaration of my M method, if I rename the dt variable to dateTime, then my third call to M in the earlier code will cause the compiler to produce the following message: error CS1739: The best overload for 'M' does not have a parameter named 'dt'.
5.Be aware that changing a parameter’s default value is potentially dangerous if the method is called from outside the module.
A call site embeds the default value into its call. If you later change the parameter’s default value and do not recompile the code containing the call site,then it will call your method passing the old default value.
You might want to consider using a default value of 0/null as a sentinel to indicate default behavior;this allows you to change your default without having to recompile all the code with call sites.
6.cannot set default values for parameters marked with either the ref or out keywords
because there is no way to pass a meaningful default value for these parameters.
when calling a method by using optional or named parameters:
1.Arguments can be passed in any order;
however, named arguments must always appear at the end of the argument list.
2.You can pass arguments by name to parameters that do not have default values,
but all required arguments must be passed (by position or by name) for the compiler to compile the code
3.C# doesn’t allow you to omit arguments between commas, as in M(1, ,DateTime.Now),because this could lead to unreadable comma-counting code.
Pass arguments by way of their parameter name if you want to omit some arguments for parameters with default values.
4.To pass an argument by parameter name that requires ref/out
C#’s optional and named parameter features are really convenient when writing C# code that interoperates with the COM object model in Microsoft Office. And, when calling a COM component, C# also allows you to omit ref/out when passing an argument by reference to simplify the coding even more. When not calling a COM component, C# requires that the out/ref keyword be applied to the argument.
The DefaultParameterValue and Optional Attributes
question:want programmers to define a method indicating which parameters are optional ,and what their default value should be in a programming language and then give programmers working in other programming languages the ability to call them.
answer:the compiler of choice must allow the caller to omit some arguments and have a way of determining what those arguments’ default values should be.
how?
In C#, when you give a parameter a default value, the compiler internally applies the System.Runtime.InteropServices.OptionalAttribute custom attribute to the parameter, and this attribute is persisted in the resulting file’s metadata.
In addition, the compiler applies System.Runtime.InteropServices.DefaultParameterValueAttribute to the parameter and persists this attribute in the resulting file’s metadata.
Then, DefaultParameterValueAttribute’s constructor is passed the constant value that you specified in your source code.
when a compiler sees that you have code calling a method that is missing some arguments,the compiler can ensure that you’ve omitted optional arguments, grab their default values out of metadata, and embed the values in the call for you automatically.
2.Implicitly Typed Local Variables
C# supports the ability to infer the type of a method’s local variable from the type of expression that is used to initialize it.
示例:
using the C# var token. To determine the type of the name variable, the compiler looks at the type of the expression on the right side of the assignment operator (=).
type; therefore, the compiler cannot infer a distinct type for it.
write String x = null; to get the same result.
In the fourth assignment,the assignment operator, too.
foreach, using, and for statements. It can also be useful when experimenting with code.
method
不能使用的情况:
1.You cannot declare a method’s parameter type by using var.
passed at a callsite and there could be no call sites or many call sites
2.type’s field by using var. There are many reasons why C# has this restriction.
should be stated explicitly.
(discussed in Chapter 10) to leak outside of a single method.
var comprare with dynamic:
Do not confuse dynamic and var.
a syntactical shortcut that has the compiler infer the specific data type from an expression.
the dynamic keyword can be used for local variables, fields, and arguments.
cast an expression to var, but you can cast an expression to dynamic.
with dynamic.
3.Passing Parameters by Reference to a Method
value.
change.
method gets its own private copy of the value type and the instance in the caller isn’t affected.
so,markedly different.
2.The CLR allows you to pass parameters by reference instead of by value.
designated parameter is passed by reference
address of the parameter rather than the parameter itself.
ref and out:
1.record whether you specified out or ref when declaring the method.
initializing the object being referred to.
the value, and the called method must write to the value before returning.
called method can read from the value and/or write to the value.
your code is correct.
3.reference types by value.
about.
that memory.
4.fields from being copied when making method calls.
5.parameters.
also define the following method in the preceding Point type.
static void Add(out Point p) { ... }
differs only on ref and out.
or ref?
do the right thing automatically.
method being called is expected to change the value of the variable being passed.
示例1:ref、out的区别
to is changed to 10
the caller.
local variable 'x'.
示例2:引用类型优化
示例3:值互换
Object references, not two String references.
优化方式二
示例四:传参匹配问题
won’t compile,because preserved.
4.Passing a Variable Number of Arguments to a Method
convenient
how to achieve?
the params keyword the parameter.
效果等同于
no Add method is defined that takes five Int32-compatible arguments;
attribute.
into an Int32 array and then calls the Add method.
written the first version that explicitly constructs and initializes the array.
compiler?
When the C# compiler detects a call to a method.
can accept the call, the compiler generates the code necessary to call the method.
the call can be satisfied.
populates its elements before emitting the code that calls the selected method.
limites?
1.Only the last parameter to a method can be marked with the params keyword (ParamArrayAttribute).
2.This parameter must also identify a single-dimension array of any type.
3.pass null or a reference to an array of 0 entries as the last parameter to the method.
4.where the parameters could be any type.
5.
memory must ultimately be garbage collected.
these scenarios will suffer a performance hit, but fortunately, they are rare.
5.Parameter and Return Type Guidelines
1.interfaces over base classes.
in a much wider range of scenarios.
2.possible (trying not to commit yourself to a specific type).
to change what your method returns, choose a weaker return type.
ICollection<String>.
6.Const-ness
why the CLR does not support constant objects/arguments?
the code from modifying any of the objects passed into the method.
1.or parameter.
and then writing to the address
that their constant objects/arguments couldn’t be written to even though they could.
2.the object/arguments.
offer any methods that can change a string object.
3.constant object/argument isn’t being mutated.
write was not occurring to a constant object, and this would hurt performance significantly
4.adds a lot of complexity for developers.
have to respect this.
also of immutable types.