New features for C # 2010 naming and optional parameters

Source: Internet
Author: User
Tags define command line net new features string version versions access
1. A named parameter allows the caller to assign a value to the parameter by supplying its name, so that the position of the parameter is not important. Optional parameters allow you to assign values to certain parameters when you define them, and you can ignore these "optional" arguments when invoked. Named and optional parameters can be applied to methods, indexers, constructors, and delegates. Named parameters and optional parameters are combined with dynamic types to facilitate access to COM APIs such as the Office Automation API.

1.1 Named parameters

The syntax for named arguments is:

Parameter name 1: Parameter value 1, parameter Name 2: Parameter value 2 ...

For example, the following code:

The following are the referenced contents:

static void Main (string[] args)
{
CreateUser (password: "AdminPassword", Name: "admin");
}

static void CreateUser (string name, string password)
{
Console.WriteLine ("Name:{0},password:{1}", name, password);
}

You can see that the position of the parameter is not important because the named argument is used at the time of the call.

1.2. Optional Parameters

The definitions of methods, constructors, indexers, and delegates can specify whether their arguments are required or optional, and must provide the required arguments when invoked, but optional arguments can be omitted.

You can also use the System.Runtime.InteropServices.OptionalAttribute attribute class to define optional parameters that have been included in the base class library since the age of 1.0.

The definition of each optional parameter contains the default value (the default value must be a constant), and if it is not specified at the time of the call, the default value is used. For example, the following code:

The following are the referenced contents:

static void Main (string[] args)
{
CreateUser ("admin", "AdminPassword", 50);
}

///


Create a user
///
User Name
User Password
points
is locked
static void CreateUser (string name, string password,
int Score=20,bool islocked=false)
{
Console.WriteLine ("Name:{0},password:{1}", name, password);
}

Define optional arguments after all the required arguments. If you provide a value for an optional parameter at call time, you must supply the value of all optional parameters before the optional parameter (if there is an optional argument before this parameter), and not allow the argument to be supplied in a comma-delimited form, which is wrong:

CreateUser ("admin", "AdminPassword", true);

and must be written:

CreateUser ("admin", "AdminPassword", 20,true);

Or a better solution is to use named parameters:

CreateUser ("admin", "AdminPassword", islocked:true);

1.3. COM API Access

Named and optional parameters, together with dynamic and other enhancements, make it easier to access the COM APIs. For example, in c#3.0 or earlier versions, when invoking certain COM APIs, if you omit some of the parameters, you need to use type.missing, such as the following code (code excerpt):

The following are the referenced contents:

var excelapp = new Microsoft.Office.Interop.Excel.Application ();
var MyFormat =
Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatAccounting1;

Excelapp.get_range ("A1", "B4"). AutoFormat (MyFormat, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

But with the naming and optional arguments, it's easy to write this:

 
  
  

The following are the referenced contents:

Excelapp.get_range ("A1", "B4"). AutoFormat (Format:myformat);

2. Type equivalence support (equivalence Support) (this segment is translated)

If you embed type information from a strong-named managed assembly, you can keep the type in an application loosely connected to the type in the standalone release version. This means that applications can use types in multiple versions of managed class libraries without recompiling each version.

Type embedding is often used for COM interactions, such as using automated applications in Microsoft Office. Embedded type information allows the same application to run on a machine that has a different version of Office installed. And developers can use type embedding in a fully managed solution.

The types from which you can embed in a program need to meet the following criteria:

The Assembly exposes at least one public interface.

The embedded interface uses the ComImport and GUID attribute declarations

The assembly uses ImportedFromTypeLib and an assembly-level GUID attribute annotation (by default, Visual Basic and Visual C # templates already contain the assembly's GUID attributes).

After you specify a public interface that can be embedded, you can create a class that implements these interfaces. Client programs can refer to programs that contain these public interfaces at design time and the default embed Interop types property is true to embed type information (the same effect can be achieved using the/LINK compilation switch on the command line), and the client can then create instances of those interfaces. If you create a new version of the strong-named runtime assembly, the client does not need to recompile with the new assembly, instead, the client program continues to use the version of the available assembly through the embedded type information of the public interface.

2.1. First create a strong named Interface Class library (set properties based on conditions that meet the criteria)

The following are the referenced contents:

[ComImport]
[Guid ("8DA56996-A151-4136-B474-32784559F6DF")]
public interface ISampleInterface
{
void Getuserinput ();
String Userinput {get;}
}

2.2. Create strong-named class libraries, reference interface class libraries, and define classes that implement the interfaces above:

The following are the referenced contents:

Public Classsampleclass:isampleinterface
{
Private stringp_userinput;
Public Stringuserinput {get{return p_userinput}}

Public Voidgetuserinput ()
{
Console.WriteLine ("Please enter a value:");
P_userinput = Console.ReadLine ();
}
}

2.3. Create a client application, reference an interface, and dynamically create a type using a reflection method to perform the appropriate action:

The following are the referenced contents:

Class Program
{
static void Main (string[] args)
{
Assembly sampleassembly = Assembly.Load ("TypeEquivalenceRuntime");
ISampleInterface SampleClass =
(isampleinterface) sampleassembly.createinstance ("Typeequivalenceruntime.sampleclass");
Sampleclass.getuserinput ();
Console.WriteLine (Sampleclass.userinput);
Console.WriteLine (Sampleassembly.getname (). Version.tostring ());
Console.ReadLine ();
}
}

4. Modify the client class that implements the interface, add new methods and modify the assembly version number and file version number 2.0.0.0:

The following are the referenced contents:

Public DateTime GetDate ()
{
return datetime.now;
}

5. Execute client program again, observe different (client will output new version number).

In the. NET an assembly created with managed code automatically recognizes updates, meaning that no additional attribute definitions are required, the interface is created directly, the interface class library and the client class are implemented (or no interface directly creates the class library at the client reference), and the class library is updated to the location where the client references The update is automatically detected by the client, as well. NET assembly to the benefit of developers. But using the role of type equivalence support, I think it is convenient to access the COM API, because COM may be written in other languages, there is no way to do like. NET assembly that automatically induction version change, personal opinion, expect master answer.

3. Summary

Dynamic types, named parameters, optional parameters, and type equivalence support are provided in Visual C # for programming convenience and more convenient for accessing COM APIs. And Microsoft's repeated references to words such as office mean that Microsoft is constantly encouraging programmers to constantly develop some of its applications in office, or whether it is now growing in office applications or growing interaction with Office in applications Consolidate Microsoft's position by making these jobs more convenient through enhanced features? Opinion, please do not hesitate to enlighten.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.