c++程序员学c# 基础
参考:C# 教程 https://www.runoob.com/csharp/csharp-tutorial.html
VS安装C#以后,有一个文档专门介绍C#语法,而且是中文版:《CSharp Language Specification.docx》
基础语法区别
?
与??
可空类型
int? num1 = null;// 一个?代表可空类型
double num3;
num3 = num1 ?? 1.23;//如果num1为null,则num3赋值为1.23
字符串常量
@代表不转义\ 可以直接分多行
string a = "hello, world"; // hello, world
string b = @"hello, world"; // hello, world
string c = "hello \t world"; // hello world
string d = @"hello \t world"; // hello \t world
string e = "Joe said \"Hello\" to me"; // Joe said "Hello" to me
string f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to me
string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt
string h = @"\\server\share\file.txt"; // \\server\share\file.txt
string i = "one\r\ntwo\r\nthree";
string j = @"one
two
three";
out ref 传出和引用
和c++函数传参的&相似
区别: out只出不进,即传入的参数的值视为null ref有进有出,等同于c++的&
class RefExample
{
static void Method(ref int i)
{
i = 44;
}
static void Method(out int i)//二者可以重载
{
i = 44;
}
static void Main()
{
int val = 0;//初始化
Method(ref val);//声明和调用都要加上ref关键字
int value;//没有初始化
Method(out value);//声明和调用都要加上out关键字
}
}
abstract 抽象
abstract class Shape //密封类
{
abstract public int area();//抽象方法 约等于c++的 =0
}
接口(Interface)
接口定义了属性、方法和事件,这些都是接口的成员。接口只包含了成员的声明。
interface IParentInterface
{
void ParentInterfaceMethod();
}
interface IMyInterface : IParentInterface
{
void MethodToImplement();
}
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
iImp.ParentInterfaceMethod();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
public void ParentInterfaceMethod()
{
Console.WriteLine("ParentInterfaceMethod() called.");
}
}
抽象类和接口
抽象类:
- 抽象方法只作声明,而不包含实现,可以看成是没有实现体的虚方法
- 抽象类可以但不是必须有抽象属性和抽象方法,但是一旦有了抽象方法,就一定要把这个类声明为抽象类
- 具体派生类必须覆盖基类的抽象方法
- 抽象派生类可以覆盖基类的抽象方法,也可以不覆盖。如果不覆盖,则其具体派生类必须覆盖它们。
- 抽象类不能被实例化
接口:
- 接口不能被实例化
- 接口只能包含方法声明
- 接口的成员包括方法、属性、索引器、事件
- 接口中不能包含常量、字段(域)、构造函数、析构函数、静态成员。
- 接口中的所有成员默认为public,因此接口中不能有private修饰符
- 派生类必须实现接口的所有成员
- 一个类可以直接实现多个接口,接口之间用逗号隔开
- 一个接口可以有多个父接口,实现该接口的类必须实现所有父接口中的所有成员。
相同点:
- 都可以被继承
- 都不能被实例化
- 都可以包含方法声明
- 派生类必须实现未实现的方法
区别:
- 抽象基类可以定义字段、属性、方法实现。接口只能定义属性、索引器、事件、和方法声明,不能包含字段。
- 接口可以被多重实现,抽象类只能被单一继承
- 抽象类是一个不完整的类,需要进一步实现(继承,并实现方法)。接口是一个行为规范,可以直接继承引用
- 接口基本不具备继承的特性,仅仅能够调用而已。
- 接口可以用于支持回调,而继承并不具备这个特点。
原文链接:https://blog.csdn.net/hemingyang97/article/details/81415124
类封装 作用域
public:所有对象都可以访问;
internal:同一个程序集的对象可以访问;即当前项目可访问
protected:只有该类对象及其子类对象可以访问
protected internal:访问限于当前程序集或派生自包含类的类型
private:对象本身在对象内部可以访问;
- 类声明只能使用 public 或 internal,internal为默认值
- 类的成员默认为 private
运算符重载
需要加static关键字
public static Box operator+ (Box b, Box c)//需要加static关键字
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}