Basic concepts related to classes ---- Beginning Visual C #,

Source: Internet
Author: User
Tags microsoft c

Basic concepts related to classes ---- Beginning Visual C #,
For more articles, see my personal homepage: zhongxiewei.com.

 

Class Definition

Modifier of the definition class:

  • Internal (default access modifier), the code in the current project has access to it
  • Public (access modifier) to make public its accessibility
  • Abstract indicates that this class is an abstract class and cannot be instantiated. It can only be inherited and can have abstract members.
  • Sealed, cannot be inherited

Note the following for class modifiers:

  • No private or protected Modifier
  • The public class cannot inherit from the internal class, as shown in figurepublic class MyClass : MyBase {} // MyBase is a internal classBut internal can inherit from the public class.
  • When an abstract class is inherited, all abstract members must be initialized unless the current class is abstract.
  • Multi-inheritance is not allowed during inheritance.
  • In the class definition, the parent class and interface both exist. The parent class must be located at the first position after the colon, for example:public class MyClass : MyBase, IMyInterface {}
Interface Definition

Modifier for defining interfaces:

  • Internal (default access modifier), the code in the current project has access to it
  • Public (access modifier) to make public its accessibility

Note that:

  • No sealed, abstract Modifier
  • Allow multiple inheritance of interfaces
  • When an interface is inherited by a class, all functions in the interface must be implemented.
System. Object

When the class does not inherit objects, the System. Object is inherited by default, so it is necessary to check what exists in the class.

Method Description
Object () Constructor
~ Object () Destructor
Virtual bool Equals (object) This and other objects for comparison
Static bool Equals (object, object) Compare the two input objects. Call the previous function internally. true all null
Static bool ReferenceEquals (object, object) Compare whether two input objects are referenced by the same object
Virtual string ToString () The class name is returned by default.
Object MemberwiseClone () Create a new object instance and copy the member variables. The referenced member variables still reference the same variable.
System. Type GetType () Type of the returned object
Virtual int GetHashCode () Returns the hash value of an object.

Example of using GetType:

if (myObj.GetType() == typeof(MyComplexClass)){    // myObj is an instance of the class MyComplexClass}
Class member Definition

Modifier Keyword:

  • Public, any code can access
  • Private, internal code of the class can access
  • Internal, internal code of the project can access
  • Protected, the inherited subclass code can access
  • Static: a member of a class, not just an object.

Modifier for member variables only:

  • Readonly, read-only variable, initialized in declaration or constructor

Modifier for member functions only:

  • Virtual, a function that can be overloaded
  • Abstract: a function that must be overloaded can only exist in the abstract class.
  • Override: overload functions in the base class
  • Extern. The function is defined elsewhere.
  • Sealed, function cannot be further overloaded
Attribute Definition
private int myInt;public int MyIntProp{    get    {        return myInt;    }    set    {        if (value >= 0 && value <= 10)            myInt = value;        else            throw(...);    }}
Hide functions in the base class

The implementation method is as follows:

public class MyBaseClass{    public void DoSomething()    { // base implementation    }}public class MyDerivedClass : MyBaseClass{    public void DoSomething()    { // Derived class implementation, hides base implementation    }}

However, the above Code generates a warning during compilation, saying that the DoSomething function in MyDerivedClass hides the DoSomething function in the base class. Please use the new Keyword, that ispublic new void DoSomething() {}.

Collection

You can use the existing System. Collections. ArrayList. Here we will talk about customizing Collections. You can achieve this by using the following methods:

Public class Animals: CollectionBase {// Add function public void Add (Animal newAnimal) {List. add (newAnimal);} // Remove public void Remove (Animal oldAnimal) {List. remove (oldAnimal);} // implement the MyAnimal [0] access method public Animal this [int animalIndex] {get {return (Animal) List [animalIndex];} set {List [animalIndex] = value ;}} public Animals (){}}
Operator overload

The member functions of the overload operators are public and static. Note that there are two additional keywords in the definition of the member function for variable conversion.ExplicitAndImplicit.

// Binary operator + public class Class1 {public int val; // binary operator public static Class1 operator + (Class1 op1, Class1 op2) {Class1 returnVal = new Class1 (); returnVal. val = op1.val + op2.val; return returnVal;} // unary operator,-public static Class1 operator-(Class1 op1) {Class1 returnVal = new Class1 (); returnVal. val =-op1.val; return returnVal ;}}
Is operator and as operator

Is OPERATOR: detects that an unknown variable can be converted to a variable of a known type. If yes, true is returned; otherwise, false is returned. However, it does not determine whether the two types are the same.

Its syntax structure is:<operand> is <type>

The possible results of this expression are as follows:

  • If type is of the class type<operand>It is also the type, or the subclass of that class, or can be converted to that type, the returned result is true.
  • If 'type' is 'interface' type, the return value is 'true' when operand' is of that type or the type is implemented.
  • If type is value type, such as int, when operand is of that type or can be implicitly converted to that type, the return result is true.

The as operator converts a variable to a special reference type.<operand> as <type>.

Applicable to the following environments,

  • If the operand type is the same.
  • If operand can be implicitly converted to type
  • If operand can be forcibly converted to type without loss.

If the conversion fails, the returned result is null.

BaseClass obj1 = new BaseClass (); DerivedClass obj2 = obj1 as DerivedClass; // return null will not throw an exception if you use... = (DerivedClass) obj1; an exception is thrown. // if the following method is used for conversion, DerivedClass derivedClass = new DerivedClass (); BaseClass baseClass = derivedClass; derivedClass newDerivedClass = baseClass as DerivedClass; // not null
Deep copy

Directly use MemberwiseClone () in the System. Object. When a class contains referenced variables, deep copy cannot be implemented, for example:

Public class Content {public int Val;} public class Cloner {public Content MyContent = new Content (); public Cloner (int newVal) {MyContent. val = newVal;} public object GetCopy () {return MemberwiseClone () ;}// call Cloner mySource = new Cloner (5); Cloner myTarget = (Cloner) mySource. getCopy (); mySource. myContent. val = 2; // This causes myTarget. myTarget. val also changed to 2.

To achieve deep copy, you can implement the ICloneable interface.

Public class Cloner: ICloneable {public Content MyContent = new Content (); public Cloner (int newVal) {MyContent. val = newVal;} public object Clone () {Cloner clonedCloner = new Cloner (MyContent. val); return clonedCloner; // or // Cloner clonedCloner = new Cloner (); // clonedCloner. myContent = MyContent. clone (); // return clonedCloner ;}}
Custom exception

In a custom process, you only need to inheritExpectionClass. For example:

public class AgeBelowZeroException : Exception{    public AgeBelowZeroException() :        base("The age must >= 0")    {    }}

Basic concepts of C Language

There are two types of floating points: Single-precision and double-precision,
Its type specifiers are float Single-precision specifiers and double-precision specifiers. In Turbo C, the single-precision model occupies 4 bytes (32-bit) memory space. The value range is 3.4E-38 ~ 3.4E + 38. Only seven valid digits are allowed. The dual-precision model occupies 8 bytes (64-bit) memory space, and the value range is 1.7E-308 ~ 1.7E + 308, which provides 16 valid digits.
The format and writing rules of real variables are the same as those of integer types.
For example: float x, y; (x, y is the actual type of single precision)
Double a, B, c; (a, B, c is the actual amount of double Precision)
Actual constants are processed in double type regardless of single or double precision.

VisualC # can be the same as Visual C?

There are some differences, but it is easy to get started with C # People who know VC ++. It contains some syntax styles of vc ++ and adds new content. Extended development platform, compatible with many languages.
C # (read as "C sharp", Chinese translated as "sharp") is an object-oriented operation released by Microsoft. the advanced programming language on the NET Framework, and is scheduled to appear on the Microsoft Professional Developer Forum (PDC. C # is the latest achievement of Microsoft researcher Anders Hejlsberg. C # Looks Like Java. It includes a single inheritance, interface, almost the same syntax as Java, and the process of compiling to intermediate code before running. however, C # is obviously different from Java. It draws on a feature of Delphi and is directly integrated with COM (Component Object Model) and is a Microsoft Company. NET windows network framework.

In this article, I will examine the general motives for creating a new computer language, and specifically specify the reasons for the emergence of C. then I will introduce the similarities between C # and Java, c, and c ++. next, I will discuss some high-level and basic differences between Java and C. I will end this article by measuring the knowledge (or lack of such knowledge) I need to develop large applications in multiple languages. NET and C. currently, C # And. NET can only be obtained in the C # language rules, as well as a "d preview version" of Windows 2000, as well as the rapidly increasing number of document sets on MSDN (not finalized yet ).

Microsoft c # language definition is mainly inherited from C and C ++, and many elements in the language also reflect this point. C # The designer has a wider range of Optional options inherited from C ++ than Java (for example, structs). It also adds its own new features (for example, source code version definition ). however, it is too immature to crush Java. C # It also needs to evolve into a language that developers can accept and adopt. microsoft is also worth noting for its new language. at present, the response is: "This is a counterattack against Java."

C # It is more like Java, although Microsoft remains silent on this issue. this is also unexpected. I think Because Java has been very successful recently, companies that use Java have reported that they have improved production efficiency than C ++.

The huge impact of Java and the wide acceptance of it have been clearly illustrated by the number of programmers working on this language and platform (it is estimated that 2.5 million of the world's programmers use Java ). the number of applications written in this language is surprising and has penetrated every level of computing, including wireless computing and mobile phones (such as Java phones invented in Japan ). C # Can I receive such courtesy in the user field? We have to wait and wait, just like Kalpathi S, CEO and chairman of SSI. as Suresh pointed out, "I found that all these are gradual. if C # does not exist, we can always return to Java or C and C ++. these are not completely new technologies; they are just marketing gimmicks made by large companies in a larger sense. we must give them time to settle down and see if these have any influence on the IT industry."

C # features inherited from Java

Class: the class declaration in C # is very similar to that in Java. this is reasonable because experience tells us that the Java model works well. the Java keyword import has been replaced with using, which plays the same role. the starting point for a class to start execution is the static method Main (). the following Hello World program shows the basic form:

Using System;

Class Hello
{

Static void Main ()
{

Console. WriteLine ("Hello, worl... the remaining full text>

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.