C# 语言基础

类型

C#是一种强类型语言,这种语言,必须声明每个要创建对象的类型,类型分为两类:内置类型用户定义类型;也可以按存储方式分为值类型引用类型。值类型将自身的值存储在栈中,而引用类型将自身的地址保存在栈中,但实际对象存储在堆中。

内置类型

C#语言提供了现代语言中通常应该提供的所有内置类型,每种类型都对应着.NET CLS(Common language specification)规范所支持的一种底层类型。

内置类型有sbyte,byte,char,bool,short,ushort,int,uint,long,ulong,float,double,decimal

除此之外,还有两种值类型enumstruct

内置类型的选择

对于内置类型的选择,考虑到内存的相对廉价,开发人员时间的宝贵,大多数情况整数可以把变量声明为int,小数float就足够了,注意编译器会默认带小数点的数为double,要赋值一个float 字面量,后面还要带上已给字母f:

float someFloat=56f;

内置类型的转换

一个类型的对象可以隐式或显式地转换为另一个类型。隐式转换是自动的进行,编译器自动转换;显示转换 需要我们明确地表示将值进行强制类型转化。

隐式转换是自动进行的,不会损失信息,例如可以隐式从short(2字节)转换为int(4字节),无论short值为何,转换为int都不会有问题,

但是,如果反方向转换,肯定损失信息,这种情况下,编译器不会执行从int到shor的隐式转换:

image-20210801144602736

这种情况下,就需要强行进行显式转换:

image-20210801144944259

如果int中的值比32767大,将在转换中被截断:

image-20210801145603642

变量与常量

创建变量是通过声明类型并给它取一个名字完成的,可以在声明类型时初始化,也可以在任何时候给变量赋值,改变原值,但在使用前必须初始化或者赋值。

常量就是恒定的变量,必须在声明时就初始化,并且初始化后不允许重新赋值,它有三种形式:字面值,符号常量,以及枚举。

在这个赋值语句中:

x=32;

32就是字面值,32的值永远是32,不能给32赋值其他新的值。

符号常量通常将一个名字指定为一个恒定值。可以使用const关键字和如下语法声明一个符号常量:

const 类型标识符 = 值;

image-20210801150423886

如果取消最后一句的注释,即给符号常量重新赋值,则会抛出错误:

image-20210801150549306

枚举

枚举的技术定义为:

[性质] [修饰符] enum 标识符 [:基类型] 
{枚举列表}

其中[]表示可选。

每个枚举都有类型,可以是任何整数类型(integer,shor,long等),但char除外。基类型是枚举的底层类型,如果省略这个选项(经常如此),将默认为int。不能在枚举列表中对每个枚举值进行声明为不同类型的值,枚举列表注意用逗号分隔。要显示一个枚举常量的值,需要将常量转换为它的底层类型,否则不会返回其值;枚举列表中,如果不特别设置,枚举从0开始,每个后续值比前一个加1.

例子:

namespace EnumeratedConstants
{
    
    class EnumeratedConstants
        
    {
        enum Tempratures
        {
            WickedCold=0,
            FreezingPoint=32,
            LightJacketWeather=60,
            SwimmingWeather=72,
            BoilingPoint=212,
        }
        enum SomeValue
        {
            First,
            Second,
            Third=20,
            Fourth
        }
        enum test
        {
             test = 0,
             test1 = 20
        }
            
        
        static void Main()
        {
            Console.WriteLine("Freezing point of water:{0}", (int)Tempratures.FreezingPoint);
            Console.WriteLine("Boiling point of water:{0}", (int)Tempratures.BoilingPoint);
            Console.WriteLine("enum SomeValue:{0},{1},{2},{3}", (int)SomeValue.First, (int)SomeValue.Second,
                (int)SomeValue.Third, (int)SomeValue.Fourth);
        Console.WriteLine("test and test1:{0},{1}", (int) test.test, (int) test.test1);
            Console.WriteLine("test and test1:{0},{1}", test.test, test.test1); //测试不对枚举常量进行转换。
        }
    }
}

输出:

image-20210801152158262

可见,不对枚举列表中的常量进行类型转换,显示不出其值。

字符串

string myString;
myString="Hello world!";

标识符

即变量的名字,必须以字母或下划线开头,Microsoft命名规范建议,变量名使用Camel记号法,方法名和其他标识符用Pascal记号法。

无条件分支语句

创建无条件分支有两种方法:一是通过方法调用,另一种是使用无条件分支关键字:goto,break,continue,return,throw

image-20210801154719528

条件分支语句

条件分支是通过条件语句创建的,条件语句用if,else,switch等关键字标识。条件分支只在条件表达式的值为true时才发生。

if-else

语法:

if (表达式)
    语句1
[else
     语句2]

[]表示可选。

例:

namespace ConditionStatement
{
    class values
    {
        static void Main()
        {
            int valueOne = 10;
            int valueTwo = 20;

            if (valueOne > valueTwo)
            {
                Console.WriteLine("valueOne:{0} is larger than valueTwo:{1}", valueOne, valueTwo);
            }
            else
            {
                Console.WriteLine("valueTwo:{0} is larger than valueOne:{1}", valueTwo, valueOne);
            }

            valueOne = 30;
            if (valueOne > valueTwo)
            {
                valueTwo = valueOne++;  // valueOne自己增加1,将自增前的值赋予valueTwo
                Console.WriteLine("\nSetting valueTwo to valueOne Value.");
                Console.WriteLine("and incrementing ValueOne.\n");
                Console.WriteLine("ValueOne:{0},ValueTwo:{1}", valueOne, valueTwo);
            }
            else
            {
                valueOne = valueTwo;
                Console.WriteLine("Setting them equal.");
                Console.WriteLine("ValueOne:{0},ValueTwo:{1}");

            }
        }
    }
}

image-20210801163836393

嵌套if

例:

namespace NestedIf
{
    class NestedIf
    {
        static void Main()
        {
            int temp = 32;
            if (temp <= 32)
            {
                Console.WriteLine("warning! Ice on road");
                if (temp == 32)
                {
                    Console.WriteLine("Temp exactly freezing,beware of water");
                }
                else
                {
                    Console.WriteLine("Temp lower than 32,watch for black ice,temp:{0}", temp);
                }
            }
        }
    }
}

image-20210801164942289

注意,C#要求if 语句只能接受布尔值,没有从数值到布尔值的转换,因此对于if (temp=32)将在编译过程中抛出错误。

switch 语句:嵌套if语句的替代方案

嵌套if语句可读性不太好,容易出错,而且难以调试。如果做出复杂选择判断,switch语句是一种强大的替代方案。switch的逻辑是选择一个匹配值,并作出相应操作。

其语法如下:

switch (表达式)
{
        case 常量表达式:
            语句
            跳转语句
        [default:语句]
}

例子:

namespace SwitchStatement
{
    class SwitchStatement
    {
        static void Main()
        {
            const int Democrat = 0;
            const int LiberalRepublication = 1;
            const int Republican = 2;
            const int Libertarian = 3;
            const int NewLeft = 4;
            const int Progressive = 5;

            int myChoice = LiberalRepublication;

            switch (myChoice)
            {
                case Democrat:
                    Console.WriteLine("You voted Democratic.\n");
                    break;
                case LiberalRepublication:
                    //此case下无语句,因此“向下执行”到下一条语句。如果语句没有内容,只能向下执行。
                    //Console.WriteLine("没有跳转语句,不能编译");
                case Republican:
                    Console.WriteLine("You voted republican.\n");
                    break;
                case NewLeft:
                    Console.WriteLine("Newleft is now Progreessive");
                    goto case Progressive;
                case Progressive:
                    Console.WriteLine("You voted Progressive.\n");
                    break;
                case Libertarian:
                    Console.WriteLine("Libertaians are voting Republican");
                    goto case Republican;
                default:
                    Console.WriteLine("You did not pick a valid choice.\n");
                    break;
            }
            Console.WriteLine("Thank you for voting.");
        }
    }
}

image-20210801214210610

在上例中,switch表达式是一个整数常量,C#还允许根据字符串跳转,因此可以写成:

case "Libertarian";

如果字符串匹配,进入case语句。

namespace SwitchStatement
{
    class SwitchStatement
    {
        static void Main()
        {
            const string Democrat = "Democrat";
            const string LiberalRepublication = "LiberalRepublication";
            const string Republican = "Republican";
            const string Libertarian = "Libertarian";
            const string NewLeft = "NewLeft";
            const string Progressive = "Progressive";

            string myChoice = "LiberalRepublication";

            switch (myChoice)
            {
                case Democrat:
                    Console.WriteLine("You voted Democratic.\n");
                    break;
                case LiberalRepublication:
                    //此case下无语句,因此“向下执行”到下一条语句。如果语句没有内容,只能向下执行。
                    //Console.WriteLine("没有跳转语句,不能编译");
                case Republican:
                    Console.WriteLine("You voted republican.\n");
                    break;
                case NewLeft:
                    Console.WriteLine("Newleft is now Progreessive");
                    goto case Progressive;
                case Progressive:
                    Console.WriteLine("You voted Progressive.\n");
                    break;
                case Libertarian:
                    Console.WriteLine("Libertaians are voting Republican");
                    goto case Republican;
                default:
                    Console.WriteLine("You did not pick a valid choice.\n");
                    break;
            }
            Console.WriteLine("Thank you for voting.");
        }
    }
}

image-20210801220241406

循环语句

goto语句

goto语句实际上应该尽量避免使用,它极易造成代码混乱,出于完整性的目的,学习一下goto用方法。

1.加一个行标,所谓行标就是后跟一个冒号的标识符。
2.goto到行标所指的行
namespace UsingGoTo
{
    class UsingGoTo
    {
        static void Main()
        {
            int i = 0;
        repeat:  //行标
            Console.WriteLine("i:{0}", i);
            i++;
            if (i < 10)
            {
                goto repeat; //尽量避免使用goto
            }
            return;
        }
    }
}

image-20210801230345243

while语句

while循环的语义是”当条件为真时,进行操作“。

语法:

while (表达式) 语句

表达式的值为布尔值(true/false),其中的语句也可以是语句块。

namespace WhileLoop
{
    class WhileLoop
    {
        static void Main()
        {
            int i = 0;
            while (i < 10)
            {
                Console.WriteLine("i:{0}", i);
                i++;
            }
            //return;
        }
    }
}

image-20210801231247712

do-while 语句

很多时候,while并不能满足需求,在一些场合,需要将”当为真时,运行“转换为”运行,当条件为真时“。即先进行操作,再检查条件。这就需要do-while循环。

do 语句 while 表达式
namespace DoWhile
    {
        class DoWhile
        {
            static int Main()
            {
                int i = 11;
                do
                {
                    Console.WriteLine("i:{0}", i);
                    i++;
                }
                while (i < 10);
                return 0;
            }
        }
    }

image-20210801232315499

namespace DoWhile
    {
        class DoWhile
        {
            static int Main()
            {
                int i = 11;
                do
                {
                    Console.WriteLine("i:{0}", i);
                    i--;
                }
                while (i >6);
                return 0;
            }
        }
    }

image-20210801232435533

for 循环

for ([初始化语句];[测试变量表达式];[变量递增]) 语句
namespace ForLoop
{
    class ForLoop
    {
        static void Main()
        {
            for (int i = 0; i < 100; i++)
            {
                Console.Write("{0} ", i);
                if (i % 10 == 0)
                {
                    Console.Write("\t{0}\n", i); //相当于Console.WriteLine("\t{0}",i};
                }
            }
        }
    }
}

image-20210802225007965

continue 和break

continue是终止当次循环,进入下一循环,而break是终止循环。

image-20210802231449086

操作符

增量和减量操作符

  • 计算和重赋值操作符

特殊自赋值操作符,如-=, +=, *=, /=, %=,自增1,和自减1很常见,要自增1,用++,自减1,用--

前缀和后缀操作符

firstValue=secondValue++;后缀
firstValue=++secondValue;前缀

后缀会先赋值,后自增(可这样帮助记忆:secondValue++,分别是先secondValue,然后++,因此是先赋值,然后自增);

前缀是先自增,后赋值(可这样帮助记忆,++secondaValue,分别是先++,后secondValuee,即先自增,后赋值 )

namespace PrefixPostfix
{
    class PrefixPostfix
    {
        static void Main()
        {
            int valueOne = 10;
            int valueTwo;
            valueTwo = valueOne++;
            Console.WriteLine("After postfix:{0},{1}", valueOne, valueTwo);

            valueOne = 20;
            valueTwo = ++valueOne;
            Console.WriteLine("After prefix:{0},{1}", valueOne, valueTwo);
        }
    }
}

image-20210803224703055

计算短路

对于

int x=8;
if ((x==8) || (y==12));

判断了x==8为true,则右边y==12将不被执行。

同理:

int y=5;
if ((y==4) && (a==9));

右边也将不再执行。

三元操作符

语法:

条件表达式? 表达式1:表达式2;

如果表达式为true,返回表达式1的结果,否则返回表达式2的结果。

例:

namespace TernaryOperator
{
    class TernaryOperator
    {
        static void Main()
        {
            int valueOne = 10;
            int valueTwo = 20;

            int maxValue = (valueOne > valueTwo) ? valueOne : valueTwo;
            Console.WriteLine("maxValue is {0}", maxValue);
        }
    }
}

image-20210803225716935

posted @ 2021-08-03 22:58  JohnYang819  阅读(126)  评论(0编辑  收藏  举报