案例1:
static void Main(string[] args)
{
int i = 2;
int s = -3;
i = +s;//正数
Console.WriteLine(i.ToString());
i = -s;//变成负数
Console.WriteLine(i.ToString());、
}
案例2:
int i1 = 2;
int i2 = 3;
int i3 = 4;
i1 = -++i2 + i2 * ++i3 + i3;
Console.WriteLine(i1);//21
//运算符 ++(元素) +(一元) 最高,* / 第二 ,+ 第三, = 、*=第四,++(后缀)最后
案例3:
static void Main(string[] args)
{
start:
int i = 5;
goto addval;
writeResul:
Console.WriteLine(i);
goto start;
addval:
i += 10;
goto writeResul; //goto语句形成了 无限循环
}
案例4:
public class MyLoveStory
{
public static void Main(string[] args)
{
Console.WriteLine("数字\t平方\t立方");
int[] ints = { 0,1,2,3,4,5,6,7,8,9};
for (int i = 0; i < ints.Length; i++)
{
Console.WriteLine("{0}\t{1}\t{2}",ints[i],pingfang(ints[i]),lifang(ints[i]));
}
}
static int pingfang(int i)//起一个函数方法
{
return i * i;
}
static int lifang(int i)//起一个函数方法
{
return i * i * i;
}
}
案例5:
public class MyLoveStory
{
public static void Main(string[] args)
{
BookStore mybook = new BookStore();//申明一个变量,建立对象
mybook.Bookage = 23;
mybook.Bookname = "cisco";
string name = "Mr.w";
mybook.Welcome(name);//调用类的方法
}
}
class BookStore//建立一个类
{
private string bookname;
private int bookage;
public string Bookname
{
get { return bookname; }
set { this.bookname = value; }
}
public int Bookage
{
get { return bookage; }
set { this.bookage = value; }
}
public void Welcome(string name)//建立类的方法
{
Console.WriteLine("欢迎{0}进入图书库!",name);
}
}
案例6:
public class MyLoveStory
{
public static void Main(string[] args)
{
BookStore mybook = new BookStore("Nothing",0);//申明一个变量,建立对象,这里要注意是用一个变量来引用一个对象
Console.WriteLine(mybook.Bookage+"\n"+mybook.Bookname);//输出默认的类的变量的值
mybook.Bookage = 23;
mybook.Bookname = "cisco";
string name = "Mr.w";
Console.WriteLine(mybook.Bookage + "\n" + mybook.Bookname);//输出赋值之后的变量的值
mybook.Welcome(name);//调用类的方法
}
}
class BookStore//建立一个类
{
private string bookname;
private int bookage;
public BookStore(string name,int age)//构造函数的作用就是初始化类里的变量
{
bookname = name;
bookage = age;
}
public string Bookname
{
get { return bookname; }
set { this.bookname = value; }
}
public int Bookage
{
get { return bookage; }
set { this.bookage = value; }
}
public void Welcome(string name)//建立类的方法
{
Console.WriteLine("欢迎{0}进入图书库!",name);
}
}
案例7:
class Program
{
static void Main(string[] args)
{
Account account1 = new Account(50.00m);
Account account2 = new Account(-7.00m);
Console.WriteLine("{0:C}",account1.Balance);//50
Console.WriteLine("{0:C}", account2.Balance);
}
}
class Account
{
//变量使用前_,属性使用大写开头
private decimal _balance; //私有变量
public Account(decimal i)//构造函数
{
Balance = i;//这里是易错的,如果你把Balance写成小写的话,那么下面的if就没用了。。。
}
public void Credit(decimal amount)//无返回值方法
{
_balance += amount;
}
public decimal Balance//属性
{
get { return _balance; }
set
{
if (value >= 0)
{
this._balance = value;
}
}
}
}