C#学习笔记(四)——变量的更多内容

一、类型转换

1、转换的类型

image

2、隐式转换

      bool 和string 没有隐式转换,具有隐式转换的都列在下面的表格

image

image

         记住一个规律,就是由精度低的类型转到精度高的类型是很容易的

3、显式转换

(1)强制类型转换

double c=2.2;
int a = (int)c;

       但是会有数据丢失的情况,但是C#为我们提供了关键字让我们很方便的来查询是发生了数据的丢失

(2)check()    uncheck()

a、格式

image

b、例子

byte destinationVar;
            short sourceVar = 291;
            destinationVar = unchecked((byte)sourceVar);
            Console.WriteLine("sourceVar val:{0}", sourceVar);
            Console.WriteLine("destinationVar val:{0}", destinationVar);
            Console.ReadKey();

        执行这段代码的时候程序就会崩溃,然后就会在错误窗口中显示这个错误。

image   

       如果是uncheck的话

image

       所以是很有用的哦、

c、我们可以设置VS让其直接对每个类型转换进行check而不需要我们自己重复性的写这个关键字,如果不想check的话只需要打上uncheck的关键字就好了。

步骤如下:

image

打开项目属性

image

点击高级。

image

勾上这个就好了。

(3)使用convert进行转换

image

这个很方便我们进行转换,而且这个会自动进行check操作,不需要设置也可以,所以很方便的

二、复杂的变量类型

1、枚举

(1)用enum关键字来定义一个枚举类型

image     image

a、在默认情况下,每个值会根据定义的顺序(0,1,2,3……),当然也可以在定义的时候使用赋值符号“=”来重新定义顺序.,没有定义的就是比前一个多1.

b、而且还可以选择指定数据的基类型(underlyinType)这个类型。是不是很赞!这个用法就可以让我用一个枚举类型作为另一个枚举类型的基类,这是一个很方便的地方哦。

(2)把字符串转换成枚举类型

image

     (enumerationType)是使用显示转化,强行转化成枚举类型;

     而后面这个方法Enum.Parse(,)会将字符串转换成枚举其中的一个子值。

2、结构

(1)定义

image

       跟C语言基本一样一样的。但是其中的<memberDeclarations>有不同,需要按照下面的格式定义。

image

accessibility:关键字可以填public  private  public,现在我们先默认使用public,这样的话就可以随意访问结构体中的数据成员。

type:数据的类型

name:变量的名字。

(2)例子

namespace Exercise
{
    enum oriantation :byte
    {
        north =1,
        south=2,
        east=3,
        west=4
    }

    struct route
    {
        public oriantation direction;
        public double distance;
    }



    class Program
    {
        static void Main(string[] args)
        {
            route myRoute;
            int myDirection = -1;
            double myDistance;
            Console.WriteLine("1) North
2) South
3) East 
4) West
");
            do
            {
                Console.WriteLine("Select a direction");
                myDirection = Convert.ToInt32(Console.ReadLine());

            } while ((myDirection < 1) || (myDirection > 4));

            Console.WriteLine("Input a distance");
            myDistance = Convert.ToDouble(Console.ReadLine());

            myRoute.direction = (oriantation)myDirection;
            myRoute.distance = myDistance;

            Console.WriteLine("myRoute spacifies a direction of {0} and distance of {1}", myRoute.direction, myRoute.distance);

            Console.ReadKey();
        }
    }
}

ps:这个例子是一个包括了枚举和结构体的一个简单的demo

3、数组

(1)声明数组

<baseType>[]  name;

        其中baseType可以是各种类型,无论是枚举还是结构体还是其他的简单变量都是可以的。

(2)初始化方式

a、以字面的形式指定数组的完整内容

int[ ] myIntArray = {3,4,5,6,6,7}

b、指定数组大小,然后再用new来初始化

int[] myIntArray = new int[5];

      对于数组变量的话,每个元素的默认值为0,而不是一个乱码。且也可以指定内容

int[] myIntArray = new int[5]{3,4,5,6,7};

      但注意new开了几个空间就一定要定义几个空间,否则报错。

c、当然也可只声明,暂时不初始化也是可以的

int[] myIntArray;
myIntArray = new int[5];

(3)例子

namespace Exercise
{

    class Program
    {
        static void Main(string[] args)
        {
            string[] myString = { "a", "b", "c" };
            int i;
            Console.WriteLine("Here are {0} of my string:", myString.Length);
            for(i=0;i<myString.Length;i++)
            {
                Console.WriteLine(myString[i]);

            }
            Console.ReadKey();
        }
    }
}

执行结果

image

(4)foreach循环

foreach(<baseType> <name> in <array>)
{
       //can use <name> for each element
}

       这个循环会迭代每个元素,依次把每个元素放在变量<name>中,且不存在访问非法元素的危险,因此不需要考虑数组中有多少个元素,并可以确保将在循环中使用每个元素。然后我们修改下上面的例子,

namespace Exercise
{

    class Program
    {
        static void Main(string[] args)
        {
            string[] myString = { "a", "b", "c" };
            
            Console.WriteLine("Here are {0} of my string:", myString.Length);
           
            foreach(string mystring in myString)
           {
               Console.WriteLine(mystring);
           }

            Console.ReadKey();
        }
    }
}

        但这样使用的话,只能访问数组中的元素而不可以对他进行修改。

(5)多维数组

a、声明

       二维数组的声明方法

<baseType>[,] <name>;

        多维数组的声明方法

<baseType>[,,,] <name>;

            这里是一个四维数组的声明方法。

b、初始化

double[,] hillHeight = new double [3,4];

c、依旧可以使用foreach对多维数组进行遍历。

(6)数组的数组

a、初始化

int[][] jaggedIntArray;
jaggedIntArray = new int[2][];
jaggedintArray[0] = new int [4];
jaggedintArray[1] = new int [3];

b、使用foreach的时候也要嵌套2层进行使用

foreach(int[]  a in aArray)
{
     foreach(int element in a)
      {
 
      }
}

4、字符串的处理

(1)string类型变量可以看作是char数组的只读书组。所以我们可以对string的每个字符进行访问,但是没有办法对其进行修改

(2)但是C#封装好了从string 转换成char类型数组的方法

string myString = "A string";
char [] maChars = myString.ToCharArray();

之后我们就可以对char数组进行处理。

(3)然后string也有封装好直接获得长度的方法,即Length

(4)将字符串全部转换为小写

<string>.ToLower()

         将字符串全部转换为大写

<string>.ToUpper()

         但是请留意,这两个函数是有返回值的,即就是把转换好的字符串返回回来,而不是直接对原字符串进行修改

(5)删除字符串中的空格

<string>.Trim();

        也可以用这个指令删除其他的字符,只要在一个char数组中保存这些字符就好了。

char[] trimChars = {' ','e','s'};
string userRsponse = Console.ReadLine();
userRespone = userRespone.ToLower();
userRespone = userRespone.Trim(trimChars);
if(userResponse == "y")
{
       //do something
}

         这里的代码就可以删除字符串中的空格,e和s。

<string>.TrimStar();       // 把字符串前面的空格删掉
<string> TrimEnd();       //把字符串后面的空格删掉

(6)在左边或者右边添加字符

<string>.PadLeft();
<string>.PadRight();
//语法如下
<string>.PadX{<desiredLength>};

例如:

myString = "Aligned";
myString = myString.PadLeft(10);

      就是在字符串的左边加上了3个空格,这样的话,长度就是10啦。

      然后不仅仅可以加空格,亦可以是其他的字符。

myString = "Aligned";
myString = myString.PadLeft(10,‘-’);

      这样就是在前面添加3个减号。

(7)例子

namespace Exercise
{

    class Program
    {
        static void Main(string[] args)
        {
            string myString = "This is a string";
            
char[] separator = { ' ' }; string[] myWords; myWords =
 myString.Split(separator);//将句子在空格处分割开来,然后变成新的字符串,存进去。
            foreach(string word in myWords)
            {
                Console.WriteLine(word);
            }

            Console.ReadKey();
        }
    }
}

运行结果

image

这一章就可以到此结束啦,大家快去实践实践吧。

原文地址:https://www.cnblogs.com/BlueMountain-HaggenDazs/p/4007517.html