A comparative Overview of C # Chinese version (iii)

Source: Internet
Author: User
Tags array bool class operator manual execution final implement requires
Chinese 10. Operator Overloading
With operator overloading, programmers can create classes that feel natural like simple types such as int, long, and so on. C # implements a restricted version of the C + + operator overload, which enables excellent examples such as the plural class operator overloads to perform well.
In C #, the operator = = is a non-virtual (operator-not-virtual) method of an object class, which is compared by reference. When you build a class, you can define your own = = operator. If you use your class in a collection, you should implement the IComparable interface. This interface has a method called CompareTo (object), and if "this" is greater than, less than, or equal to this object, it should return a positive, negative or 0 accordingly. If you want users to be able to use your classes in elegant syntax, you can choose to define <, <=, >=, > methods. numeric types (int, long, and so on) implement the IComparable interface.
Here is a simple example of how to handle equal and compare operations:
public class Score:icomparable
{
int value;
Public Score (int Score)
{
Value = score;
}
public static BOOL operator = = (Score x, Score y)
{
return x.value = = Y.value;
}
public static bool operator!= (Score x, Score y)
{
return x.value!= Y.value;
}
public int CompareTo (object o)
{
return value-((Score) O). Value;
}
}
Score a = new Score (5);
Score B = New Score (5);
Object C = A;
Object d = b;
Compare A and B by reference:
System.Console.WriteLine (object) A = = (object) b;//The result is false
The previous code should be: System.Console.WriteLine ((object) A = = (object) b); The result is false "
Compare values for A and B:
System.Console.WriteLine (A = = B); The result is true
Compare C and D by reference:
System.Console.WriteLine (c = d); The result is false
Compare the values of C and D:
System.Console.WriteLine (((IComparable) c). CompareTo (d) = = 0); The result is true
You can also add <, <=, >=, > Operators to the Score class. C # must be defined together to ensure that the operators (!= and = =, > and <, >=, and <=) that appear logically to be aligned in the compile period.
11. Polymorphism
Object-oriented language uses virtual methods to express polymorphism. This means that a derived class can have a method that has the same signature as the parent class, and that the parent class can invoke the method of the derived class: This should be an object (or object reference, pointer to an object). In Java, the method is virtual by default. In C #, you must use the Virtual keyword in order for the method to be invoked by the parent class.
In C #, you also need to override the keyword to indicate how a method will overload (or implement an abstract method) its parent class.
Class B//"Should be Class B"
{
public virtual void Foo () {}
}
Class D:b//"should be class D:b"
{
public override void Foo () {}
}
Attempting to overload a non-virtual method will result in a compile-time error unless you add the "new" keyword to the method to indicate how the method intends to hide the parent class.
Class N:d//"should be class N:d"
{
Public new void Foo () {}
}
n n = new n ();
N.foo (); Call Foo of n
((D) n). Foo (); Call the Foo of D
((B) n). Foo (); Call the Foo of D
Compared to C + +, Java, C # 's override keyword makes it clear which methods are overloaded when you read the source code. However, using virtual methods has both advantages and disadvantages. The first advantage is: Avoid using virtual methods to slightly improve execution speed. 2nd, you can clearly know which methods will be overloaded. From the "however", these statements are clearly illogical, but the original is the case: "However, requiring the use of the virtual methodHas its pros and cons. The slightly increased execution speed from avoiding virtual methods. The second pro is to make clear what methods are intended to be overridden. I think the logic would be smoother if you changed the method I marked Italic to keyword. In this way, the first sentence can be considered to be compared to the Java, because the method default is virtual, the second sentence is the main and C + +, the reason for see later I related comments. However, profits can also be a disadvantage. and Java default ignore final modifier "in Java, you can use the final keyword, the method is locked, equivalent to c#/c++ in the virtual keyword to decorate method/member functions," and C + + default ignore the virtual modifier, The default option in Java is "virtual" so that you lose some of the efficiency of the program, while in C + +, it may hinder extensibility, although this for the implementation of the base class is unpredictable.
In C + +, it may be a hindrance to extensibility, which might be so understood:
Class Parentcls
{
Public
virtual void f ();
};
/////////////////////////////////////////////////////////////////////////////
Class Childcls:public Parentcls
{
Public
/*virtual*/void f (); * It is also virtual that is not marked as virtual, but Grandchildcls does not know (assuming that GRANDCHILDCLS does not see PARENTCLS), It does not know that the method should be overload (of course C + + and overload keyword, it is Object Pascal, and here again, the translation of overload and override both have been very confusing, Borland official Chinese Simplified Manual is translated as "heavy" or override, still can not touch. That is, it does not know whether the polymorphic mechanism will work in this case. Maybe you will say, try not to know the J * * *
};
Class Grandchildcls:public Childcls
{
Public
void f ();
};

12. Interface
The interfaces in C # are similar to the interfaces in Java, but have greater flexibility. A class can explicitly implement an interface arbitrarily:
public interface Iteller
{
void Next ();
}
public interface Iiterator
{
void Next ();
}
public class Clark:iteller, Iiterator
{
void Iteller.next () {}
void Iiterator.next () {}
}
This brings two benefits to the class that implements the interface. First, a class can implement a number of interfaces without having to worry about naming conflicts. Second, a class can hide a method if it does not work for the average user. The invocation of an explicitly implemented method requires that the class "should be an object" shape into an interface:
Clark Clark = new Clark ();
((Iteller) Clark). Next ();
13. Version Processing
The solution version problem has become. NET Framework is a major consideration. Most of these considerations are embodied in the composition. In C #, the ability to run different versions of the same composition in the same process is impressive.
When the new version of the code, especially. NET Library) is created, C # can prevent software from failing. The C # Language reference describes the problem in detail. I would like to use an example to succinctly explain the following:
In Java, suppose we deploy a class called D, which derives from a class called B, which is published through a VM. Class D has a method called Foo, and it does not have this method when B is released. Later, an upgrade was made to Class B, now B includes a method called Foo, and the new VM is now installed on the machine using Class D. Now, software with D may fail because a new implementation of Class B may result in a virtual function call to D, which performs an unexpected action of Class B. ": Default in Java method is virtual" in C #, the Foo method of Class D should be declared without the override modifier (this really expresses the programmer's will), so the runtime knows that the Foo method of Class D hides the Foo method of Class B instead of overloading it.
The interesting thing about quoting the C # Reference manual is that "C # deals with versioning problems by requiring the developer to be clear about their intentions." Although using override is a way of expressing intent, the compiler can automatically generate-by checking at compile time whether the method is executing (rather than declaring) an overload. This means that you can still have Java-like languages (Java without virtual and override keywords), and still be able to handle versioning problems correctly.
See Field ModifiersPart.
14. Parameter Modifiers
(1) ref parameter modifier
C # (compared to Java) allows you to pass parameters by reference. The most obvious example of this is the common Exchange method. Unlike C + +, it is not only a declaration, but also a ref indicator when invoked: "Do not misunderstand this sentence, C + + of course is not ref keyword"
public class Test
{
public static void Main ()
{
int a = 1;
int b = 2;
Swap (ref a, ref B);
}
public static void swap (ref int A, ref int B)
{
int temp = A;
A = b;
b = temp;
}
}
(2) out parameter modifiers
The Out keyword is a natural complement to the ref parameter modifier. The ref modifier requires that the parameter be assigned before the method is passed in. An out modifier explicitly assigns a value to a parameter when the method returns.
(3) params parameter modifiers
The params modifier can be added to the last parameter of the method, and the method will accept any number of parameters of the specified type: In a method declaration, only one parameter of a params property is allowed. For example:
public class Test
{
public static void Main ()
{
Console.WriteLine (Add (1, 2, 3, 4). ToString ());
}
public static int Add (params int[] array)
{
int sum = 0;
foreach (int i in array)
sum + = i;
return sum;
}
}
Author Note: A very surprising thing to learn about Java is to find that Java cannot pass parameters by reference, although you will rarely want this feature again soon, and you don't need it to write code. When I first read the C # specification, I used to think, "Why do they add this feature and I can write code without it?" After reflection, I realized that this is not really a question of whether certain functions are useful, but more about the fact that you need other conditions to achieve without it.

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.