Change from C ++ to C # Notes (6)

Source: Internet
Author: User

Introduction: every 10 years or so, programmers need to spend a lot of time and energy learning new programming technologies. In 1980s, it was Unix and C, and in 1990s it was Windows and C ++. Now it has reached Microsoft's. NETFramework and C #. Although new technologies need to be learned, the benefits are far higher than the labor cost. Fortunately, the analysis and design of most projects using C # And. NET have no essential changes in C ++ and Windows. In this article, I will introduce how to make a leap from C ++ to C.

Many articles have already introduced C #'s improvements to C ++, so I will not repeat these questions here. Here, I will focus on the biggest change from C ++ to C #: the change from an unmanageable environment to a manageable environment. In addition, I will make some mistakes that C # programmers can easily make for your reference. In addition, I will explain some new functions that C # can affect programming.

Series of articles: [switching from C ++ to C # changes that need attention (1) (2) (3) (4) (5)]

Method only

We may only care about methods, but not about fields and attributes. Therefore, we need to delete the following calls to GetMembers:


MemberInfo [] mbrInfoArray =
TheType. GetMembers (BindingFlags. LookupAll );


Then add the GetMethods statement:


MbrInfoArray = theType. GetMethods ();


Now, only the method is left in the output.


Output (excerpt)
BooleanEquals (System. Object) isaMethod
System. StringToString () isaMethod
System. stringcreatpolicifiedname (System. String, System. String)
IsaMethod
System. Reflection. MethodInfoget_EntryPoint () isaMethod


Discover specific members
Finally, to further narrow down the scope, we can use the FindMembers method to find a specific type of method. For example, in the following code, we can only search for methods starting with "Get.


PublicclassTester
{
PublicstaticvoidMain ()
{
// Check a single object
TypetheType = Type. GetType ("System. Reflection. Assembly ");
// Only Get members starting with Get
MemberInfo [] mbrInfoArray
TheType. FindMembers (MemberTypes. Method,
BindingFlags. Default,
Type. FilterName, "Get *");
Foreach (MemberInfombrInfoinmbrInfoArray)
{

Console. WriteLine ("{0} isa {1 }",
MbrInfo, mbrInfo. MemberType. Format ());
}
}
}


The output part is as follows:


System. Type [] GetTypes () isaMethod
System. Type [] GetExportedTypes () isaMethod
System. TypeGetType (System. String, Boolean) isaMethod
System. TypeGetType (System. String) isaMethod
System. Reflection. AssemblyNameGetName (Boolean) isaMethod
System. Reflection. AssemblyNameGetName () isaMethod
Int32GetHashCode () isaMethod
System. Reflection. AssemblyGetAssembly (System. Type) isaMethod
System. TypeGetType (System. String, Boolean, Boolean) isaMethod


Dynamic call

Once a method is found, you can use the ing method to call it. For example, we may need to call the Cos method in System. Math (return the cosine of an angle ). Therefore, we need to obtain the type information of the System. Math class, as shown below:


TypetheMathType = Type. GetType ("System. Math ");


With the type information, we can dynamically load an instance of a class:


ObjecttheObj = Activator. CreateInstance (theMathType );


CreateInstance is a static method of the Activator class and can be used to initialize objects.

With the System. Math class instance, we can call the Cos method. We also need to prepare an array that defines the parameter type, because Cos only needs one parameter (the angle of the cosine value is required), so only one member is required in the array. We will assign a System. Double Type object to the array, that is, the Type of parameters required by the Cos method:


Type [] paramTypes = newType [1];
ParamTypes [0] = Type. GetType ("System. Double ");


Now we can pass the method name. This array defines the Type of the parameter of the GetMethod method in the Type object:


MethodInfoCosineInfo =
TheMathType. GetMethod ("Cos", paramTypes );


Now we get the MethodInfo type object, on which we can call the corresponding method. Therefore, we need to input the actual parameter value in the array again:


Object [] parameters = newObject [1];
Parameters [0] = 45;
ObjectreturnVal = CosineInfo. Invoke (theObj, parameters );


Note that I have created two arrays. The first array named paramTypes stores the parameter type, and the second array named parameters stores the actual parameter values. If the method requires two parameters, we need to maintain two parameters for each of the two arrays. If the method does not require parameters, we still need to create these two arrays, but we do not need to store data in them.


Type [] paramTypes = newType [0];


Although it looks a bit strange, it is correct. The complete code is as follows:

Use of ing methods


UsingSystem;
UsingSystem. Reflection; publicclassTester
{
PublicstaticvoidMain ()
{
TypetheMathType = Type. GetType ("System. Math ");
ObjecttheObj = Activator. CreateInstance (theMathType );
// An array with only one member
Type [] paramTypes = newType [1];
ParamTypes [0] = Type. GetType ("System. Double ");

// Obtain information about the Cos () method
MethodInfoCosineInfo =
TheMathType. GetMethod ("Cos", paramTypes );

// Fill in the actual parameters in an array
Object [] parameters = newObject [1];
Parameters [0] = 45;
ObjectreturnVal = CosineInfo. Invoke (theObj, parameters );
Console. WriteLine (
"Thecosineofa45degreeangle {0}", returnVal );

}
}
 


Conclusion

Although many small mistakes are waiting for C ++ programmers to make, the C # syntax is not much different from C ++, and the conversion to the new language is quite easy. The interesting part of using C # is to use the Universal Language Runtime Library. This article only involves several key issues. CLR and. NETFramework provide more support for threads, collections, Internet application development, and Windows-based application development. The distinction between language functions and CLR functions is very vague, but the combination is a very powerful development tool.


 

Related Article

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.