rss· 投稿· 设为首页· 加入收藏· 繁體版
当前位置: 火魔网 » 程序开发 » C#

C#语法简明笔记

1.数据类型与变量
1)定义数据类型
  int distanceInMiles=437
  由于C#中没有DateTime类型的变量,只能直接使用System.DateTime
  尝试定义System.DateTime

2)数据类型转换
  (1)一般对象:ToString()
  Label1.Text=System.DateTime.Now.ToString();
  (2)转换Convert
   bool myBoolean1=Convert.ToBoolean("True");
  (3)强制转换
   object o1=1;
   int i1=(int)ol;
  
   double o2=1;
   int i2=(int)o2;
  (4)转换失败不会出现错误而只是空值的办法
   object o1=1;
   ArrayList myList=o1 as ArrayList
 
3)数组
  (1)定义数组
  string[] roles=new string[2]; //直接定义有两个元素
  (2)数组赋值
  roles[0]='Administrators'; //成功
  roles[1]="ContentManagers'; //成功
  roles[2]="Members"; //错误
  (3)扩充数组
  string tempRoles=new string[3];//定义临时数组
  Array.Copy(roles,tempRoles,roles.Length);// 复制数组到临时数组中
  roles=tempRoles; //将临时数组的指针指向旧数组
  roles[2]="Members";
  (4)通过泛型扩充数组(泛型是一本书,另外要学习)
  Array.Resize<string>(ref roles,3);
  roles[2]="Members";

4)无类型集合 ArrayList
  ArrayList roles=new ArrayList();
  roles.Add("Administrators");
  roles.Add("ContentManagers");
  roles.Add("Members");

5)泛型列表 List
  List<int> intList=new List<int>();
  List<bool> boolList=new List<bool>();
  List<Button> buttonList=new List<Button>();

6)泛型解释
  泛型应用在某种类中,作为参数,可以到具体实例化调用的时候才决定类型的一种定义方法.
  入下面代码例子, GenericList<T>  T这是一个类型参数,这个参数要到实际实例化才会被定义.

2.语句
1) 算术运算符
   +   加
   -    减
   *    乘
   /    除
   %    取余数
   Math.Pow(2,3)  2的3次方

2)比较运算符
 ==
 !=
 <
 >
 <=
 >=
 is    检查一个变量是否属于某种类型   

3)字符串连接运算符
  +
  +=

4)逻辑运算符
  %%  ---- And
  ||  ---- Or
  !  ---- Not
  &&  ---- AndAlso 第一个值不为True则不检查第二个值以节省运算时间

5)if Else 和 ElseIf

if (!User.IsInRole("Administrators"))
  {
 btnDeleteArticle.Visible=true;
  }
  else
  {
 btnDeleteArticle.Visible=false;
  }

 
if (!User.IsInRole("Administrators"))
  {
 btnDeleteArticle.Visible=true;
  }
  else if (!User.IsInRole("Other"))
  {
 btnDeleteArticle.Visible=false;
  } 
  else if (IsInRole("None"))
  {
 btnDeleteArticle.Visible=false;
  }
 
6)switch

switch (today.DateOfWeek)
{
  case DateOfWeek.Monday:
 discountRate=0.4;
        break;
  case DateOfWeek.Tuesday;
 discountRate=0.3;
 break
  case DateOfWeek.Wednesday;
 discountRate=0.5;
 break
  case DateOfWeek.Thursday;
 discountRate=0.9;
 break
  default:
 discountRate=0;
 break;
}

7)For 循环
for (int loopCount=1;loopCount <=10;loopCount++)
{
 Label1.Text+=loopCount.ToString()+"<br />";
}

for (int loopCount=1;loopCount <=roles.Length;loopCount++)
{
 Label1.Text+=roles[loopCount]+"<br />";
}

8) foreach 循环
foreach (string role in roles)
{
 label1.Text+=role+"<br/>
}

9) While 循环
bool success=false;
while (!success)
{
 success=SendEmailMessage();
}

3.组织代码

1)方法\函数\子例程

(1)函数
public datatype functionname([parameterList])
{
}

(2)子例程
public void SubName([ParameterList])
{
}

Public int Add(int a,int b)
{
  return a+b;
}
public void SendEmail(string emailaddress)
{
 //code to send email goes here
}

(3)函数/子例程传值或者传指针

public void ByRefDemo(ref int x)
{
 x=x+20;
}

int y=0;
ByRefDemo(ref y);

4.命名空间组织代码
(1)

顶一下
(0)
踩一下
(0)