您的位置:首页 > 其它

常用函数及方法

2005-11-03 19:01 375 查看

[b]基类转换
进制转换 字符操作常用函数方法XML操作常用函数Request.ServerVariables 环境变量集合

//基类转换
System.Convert() 类

将一个基本数据类型转换为另一个基本数据类型。
Boolean、Char、SByte、Byte、Int16、Int32、
Int64、UInt16、UInt32、UInt64、Single、
Double、Decimal、DateTime 和 String
示范:
Convert.ToInt32(n)

类型.Parse()
异常类型 条件
ArgumentNullException s 为空引用(Visual Basic 中为 Nothing)。
FormatException s 的格式不正确。
OverflowException s 表示小于 MinValue 或大于 MaxValue 的数字。

将一个string类型转换为另一个数据类型
Byte、DateTime、Decimal、Double、Enum、
FontUnit、Int16、Int32、Int64、SByte、
Single、UInt16、UInt32、UInt64、Unit、
示范:
Int32.Parse(n)

string.ToString()
 
12345.ToString("n");    //生成  12,345.00
  12345.ToString("C");    //生成 ¥12,345.00
  12345.ToString("e");    //生成 1.234500e+004
  12345.ToString("f4");   //生成 12345.0000
  12345.ToString("x");    //生成 3039 (16进制)
  12345.ToString("p");    //生成 1,234,500.00%

//进制转换

前一阶段,遇到了一个将int型数字转换成2进制显示的问题。如:8 -> 1000要求输入8就出现结果1000;输入13就出现1101。

以前没有遇到过此类问题,初一接触,第一反应就是C#必有解决此问题的方法可以直接调用。

本以为在Convert.的方法里可以直接ToBinary或是类似的处理,但经查找无此方法,于是想也许有其他方法重载了或派生了解决此问题的方法。

经查找,果然在ToString()的系列方法中有解决此问题的重载。
具体应用如:int a=13; Convert.ToString(a,2); 其中的2指转换成的基本类型是2进制类型。这样转换后就得到了1101的字符串。
同理还可以进行其他的多种进制转化。

///int.Parse \ Convert.ToString \ BitConverter.ToString

//十六进制(string)转化为十进制(int)
int i = 0xA1 ;//ASCII码A1转化为对应值 可以:string thevalue = (char) 0xA1 ;

//十进制(int)转化为十六进制(string)
int a = 188;
TextBox1.Text=a.ToString("X4") ;

//十六进制(string)转化为十进制(int)
int b = int.Parse("AB", System.Globalization.NumberStyles.HexNumber);

//十进制(int)转化为十六进制(string)
j = 10;
string strBase16 = Convert.ToString(j,16);

//十六进制(string)转化为十进制(int)
string strBase16 = "A";
int j = Convert.ToInt32(strBase16,16);

//二进制(string)转化为十进制(int)
string bin = "1110" ;
int dec= Convert.ToInt16( bin , 2 ) ;
dec.ToString ( ) ;

//十进制(int)转化为二进制(string)
int j = 10;
string strBase2 = Convert.ToString(j,2);
DataAccess.common.setMessage( strBase2 ) ;

//十进制(int)转化为二进制(string)
int dec= 14 ;
sting bin = ConvertToBin ( dec ) ;// dec/2 = "1110"

//BitConverter转化
bytes = System.Text.Encoding.Default.GetBytes( "12Paladin2" ) ;
MessageBox.Show ( BitConverter.ToString( bytes ) ) ; // 31-32-50-61-6C-61-64-69-6E-32

//字节(byte)转化为十六进制(string)
Convert.ToString ( bytes[0+1] , 16 ) ;

//&Hff转化为如255的存放在byte中
byte.Parse ( Convert.ToInt32( '\xff' )).ToString( ) ) ;

//byte中bit操作
int[] hello = new int[1];
hello[0] = 1;
System.Collections.BitArray kao = new BitArray(hello);
bool **** = kao[0];

//字符操作
1 、大小写转换
//CultureInfo.CurrentCulture。对于不区分区域性的大小写更改 如:String.ToUpper(CultuerInfo.CurrentCulture);
String.ToUpper() //字符串转大写
String.ToLower() //字符串转小写
Char.ToUpper()
Caar.ToLower();

2、变量.Length //取得变量的长度

2、字符串拆分
Regex r = new Regex("(-)"); // Split on hyphens.
string[] s = r.Split("one-two-banana");

3、Server.HtmlEncode(string) //html编码转换,输出的字符按原样输出,不执行包含的html码

4 、变量.Substring(参数1,参数2);
  截取字串的一部分,参数1为左起始位数,参数2为截取几位 如:
string s1 = str.Substring(0,2);

5 、char.IsWhiteSpce(字串变量,位数) //字符串中找空格 逻辑型
  Response.Write(char.IsWhiteSpace("中国 人民",2)); //结果为:True, 以0开始,所以2表示第三个字符。

6、char.IsPunctuation('字符') //字符串中找标点符号 逻辑型
Response.Write(char.IsPunctuation('A'));  //返回:False

7、(int)'字符' //把字符转为数字,查代码点,注意是单引号。
  Response.Write((int)'中');  //结果为中字的代码:20013

8、(char)代码 //把数字转为字符,查代码代表的字符
  Response.Write((char)22269);  //返回“国”字。
  
9、 Trim()    //清除字串前后空格

10 、字串变量.Replace("子字串","替换为")
   字串替换
   如:
   string str="中国";
   str=str.Replace(查找内容,替换为);

11、Math.Max(i,j) //取最大值
如: int x = Math.Max(5,10); //x将取值10

12、System.Text.Encoding.Default.GetBytes(变量) //把字符符转为二进制
  byte[] bytStr = System.Text.Encoding.Default.GetBytes(str); //字码转换 转为比特码
  len = bytStr.Length;   //然后可得到比特长度:

13、System.Text.StringBuilder("") // 字符串相加,(比 + 更快 )  
  System.Text.StringBuilder sb = new System.Text.StringBuilder("");
  sb.Append("中华");
  sb.Append("人民");
  sb.Append("共和国");

//常用函数方法
1、DateTime  数字型
    System.DateTime currentTime=new System.DateTime();
1.1 取当前年月日时分秒
    currentTime=System.DateTime.Now;
1.2 取当前年
    int 年=currentTime.Year;
1.3 取当前月
    int 月=currentTime.Month;
1.4 取当前日
    int 日=currentTime.Day;
1.5 取当前时
    int 时=currentTime.Hour;
1.6 取当前分
    int 分=currentTime.Minute;
1.7 取当前秒
    int 秒=currentTime.Second;
1.8 取当前毫秒
  int 毫秒=currentTime.Millisecond;
  (变量可用中文)
DateTime dat=DateTime.Now;//当前系统时间
int n=20;
DateTime dat1 = dat.AddDays(n);//添加n天
Console.WriteLine(dat1);

2、Response.Redirect("URL地址"); //跳转到URL指定的页面
   

3、String user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString(); //取远程用户IP地址
 

4、//穿过代理服务器取远程用户真实IP地址:
  if(Request.ServerVariables["HTTP_VIA"]!=null){
   string user_IP=Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
  }
else{
   string user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
  }
  
5、 Session["变量"]; 
   存取Session值;
   如,赋值: Session["username"]="小布什";

     取值: Object objName=Session["username"];
         String strName=objName.ToString();
     清空: Session.RemoveAll();

//XML常用操作

1、DOC对象.CreateElement("新建节点名"); //创建XML文档新节点
  

2、父节点.AppendChild(子节点); //将新建的子节点加到XML文档父节点下
  

3、 父节点.RemoveChild(节点); //删除节点
  

常用函数:
Abs(number) 取得数值的绝对值。
Asc(String) 取得字符串表达式的第一个字符ASCII 码。
Atn(number) 取得一个角度的反正切值。
CallByName (object, procname, usecalltype,[args()]) 执行一个对象的方法、设定或传回对象的属性。
CBool(expression) 转换表达式为Boolean 型态。
CByte(expression) 转换表达式为Byte 型态。
CChar(expression) 转换表达式为字符型态。
CDate(expression) 转换表达式为Date 型态。
CDbl(expression) 转换表达式为Double 型态。
CDec(expression) 转换表达式为Decimal 型态。
CInt(expression) 转换表达式为Integer 型态。
CLng(expression) 转换表达式为Long 型态。
CObj(expression) 转换表达式为Object 型态。
CShort(expression) 转换表达式为Short 型态。
CSng(expression) 转换表达式为Single 型态。
CStr(expression) 转换表达式为String 型态。
Choose (index, choice-1[, choice-2, ... [, choice-n]]) 以索引值来选择并传回所设定的参数。
Chr(charcode) 以ASCII 码来取得字符内容。
Close(filenumberlist) 结束使用Open 开启的档案。
Cos(number) 取得一个角度的余弦值。
Ctype(expression, typename) 转换表达式的型态。
DateAdd(dateinterval, number, datetime) 对日期或时间作加减。
DateDiff(dateinterval, date1, date2) 计算两个日期或时间间的差值。
DatePart (dateinterval, date) 依接收的日期或时间参数传回年、月、日或时间。
DateSerial(year, month, day) 将接收的参数合并为一个只有日期的Date 型态的数据。
DateValue(datetime) 取得符合国别设定样式的日期值,并包含时间。
Day(datetime) 依接收的日期参数传回日。
Eof(filenumber) 当抵达一个被开启的档案结尾时会传回True。
Exp(number) 依接收的参数传回e 的次方值。
FileDateTime(pathname) 传回档案建立时的日期、时间。
FileLen(pathname) 传回档案的长度,单位是Byte。
Filter(sourcearray, match[, include[, compare]]) 搜寻字符串数组中的指定字符串,凡是数组元素中含有指定字符串,会将它们结合成新的字符串数组并传回。若是要传回不含指定字符串的数组元素,则include 参数设为False。compare 参数则是设定搜寻时是否区分大小写,此时只要给TextCompare 常数或1 即可。
Fix(number) 去掉参数的小数部分并传回。
Format(expression[, style[, firstdayofweek[, firstweekofyear]]]) 将日期、时间和数值资料转为每个国家都可以接受的格式。
FormatCurrency(expression[,numdigitsafterdecimal [,includeleadingdigit]]) 将数值输出为金额型态。
numdigitsafterdecimal 参数为小数字数,includeleadingdigit 参数为当整数为0 时是否补至整数字数。
FormatDateTime(date[,namedformat]) 传回格式化的日期或时间数据。
FormatNumber(expression[,numdigitsafterdecimal [,includeleadingdigit]]) 传回格式化
的数值数据。Numdigitsafterdecimal 参数为小数字数,includeleadingdigit 参数为当整数为0 时是否补至整数字数。
FormatPercent(expression[,numdigitsafterdecimal [,includeleadingdigit]]) 传回转换为百分比格式的数值数据。numdigitsafterdecimal 参数为小数字数,includeleadingdigit 参数为当整数为0 时是否补至整数字数。
GetAttr(filename) 传回档案或目录的属性值。
Hex(number) 将数值参数转换为16 进制值。
Hour(time) 传回时间的小时字段,型态是Integer。
Iif(expression, truepart, falsepart) 当表达式的传回值为True 时执行truepart 字段的程序,反之则执行falsepart 字段。
InStr([start, ]string1, string2) 搜寻string2 参数设定的字符出现在字符串的第几个字符,start 为由第几个字符开始寻找,string1 为欲搜寻的字符串,string2 为欲搜寻的字符。
Int(number) 传回小于或等于接收参数的最大整数值。
IsArray(varname) 判断一个变量是否为数组型态,若为数组则传回True,反之则为False。
IsDate(expression) 判断表达式内容是否为DateTime 型态,若是则传回True,反之则为False。
IsDbNull(expression) 判断表达式内容是否为Null,若是则传回True,反之则为False。
IsNumeric(expression) 判断表达式内容是否为数值型态,若是则传回True,反之则为False。
Join(sourcearray[, delimiter]) 将字符串数组合并唯一个字符串,delimiter 参数是设定在各个元素间加入新的字符串。
Lcase(string) 将字符串转换为小写字体。
Left(string, length) 由字符串左边开始取得length 参数设定长度的字符。
Len(string) 取得字符串的长度。
Log(number) 取得数值的自然对数。
Ltrim(string) 去掉字符串的左边空白部分。
Mid(string, start[, length]) 取出字符串中strat 参数设定的字符后length 长度的字符串,若length 参数没有设定,则取回start 以后全部的字符。
Minute(time) 取得时间内容的分部分,型态为Integer。
MkDir(path) 建立一个新的目录。
Month(date) 取得日期的月部分,型态为Integer。
MonthName(month) 依接收的月份数值取得该月份的完整写法。
Now() 取得目前的日期和时间。
Oct(number) 将数值参数转换为8 进制值。
Replace(expression, find, replace) 将字符串中find 参数指定的字符串转换为replace 参数指定的字符串。
Right(string,length) 由字符串右边开始取得length 参数设定长度的字符。
RmDir(path) 移除一个空的目录。
Rnd() 取得介于0 到1 之间的小数,如果每次都要取得不同的值,使用前需加上Randomize 叙述。
Rtrim(string) 去掉字符串的右边空白部分。
Second(time) 取得时间内容的秒部分,型态为Integer。
Sign(number) 取得数值内容是正数或负数,正数传回1,负数传回-1,0 传回0。
Sin(number) 取得一个角度的正弦值。
Space(number) 取得number 参数设定的空白字符串。
Split(expression[, delimiter]) 以delimiter 参数设定的条件字符串来将字符串分割为字符串数组。
Sqrt(number) 取得一数值得平方根。
Str(number) 将数字转为字符串后传回。
StrReverse(expression) 取得字符串内容反转后的结果。
Tan(number) 取得某个角度的正切值。
TimeOfDay() 取得目前不包含日期的时间。
Timer() 取得由0:00 到目前时间的秒数,型态为Double。
TimeSerial(hour, minute, second) 将接收的参数合并为一个只有时间Date 型态的数据。
TimaValue(time) 取得符合国别设定样式的时间值。
Today() 取得今天不包含时间的日期。
Trim(string) 去掉字符串开头和结尾的空白。
TypeName(varname) 取得变量或对象的型态。
Ubound(arrayname[, dimension]) 取得数组的最终索引值,dimension 参数是指定取得第几维度的最终索引值。
Ucase(string) 将字符串转换为大写。
Val(string) 将代表数字的字符串转换为数值型态,若字符串中含有非数字的内容则会将其去除后,合并为一数字。
Weekday(date) 取的参数中的日期是一个星期的第几天,星期天为1、星期一为2、星期二为3 依此类推。
WeekDayName(number) 依接收的参数取得星期的名称,可接收的参数为1 到7,星期天为1、星期一为2、星期二为3 依此类推。

ASP.NET 中的 Request.ServerVariables 环境变量集合

测试的url地址是http://www.test.com/testweb/default.aspx, 结果如下:

Request.ApplicationPath : /testweb ----获取服务器上 ASP.NET 应用程序的虚拟应用程序根路径
Request.CurrentExecutionFilePath : /testweb/default.aspx 获取当前请求的虚拟路径
Request.FilePath : /testweb/default.aspx 获取当前请求的虚拟路径
Request.Path : /testweb/default.aspx
Request.PathInfo :
Request.PhysicalApplicationPath : E:\WWW\testweb\
Request.PhysicalPath : E:\WWW\testweb\default.aspx
Request.RawUrl : /testweb/default.aspx
Request.Url.AbsolutePath : /testweb/default.aspx
Request.Url.AbsoluteUri : http://www.test.com/testweb/default.aspx Request.Url.Host : www.test.com
Request.Url.LocalPath : /testweb/default.aspx
Request.UrlReferrer.ToString() : 获取有关客户端上次请求的 URL 的信息

其它属性:
using System.Net. Dns.GetHostName(); //取得计算机名

=Environment.OSVersion.ToString() //操作系统
NET RTL 版本:=Environment.Version

下列使用示范:
Page.Request.UserHostAddress //取得游览者IP地址
Request.ServerVariables["REMOTE_ADDR"]//取客户端IP,如有代理得到的是代理服务器IP,而不是客户端IP地址。
Request.ServerVariables["HTTP_X_FORWARDED_FOR"]//透过代理取客户端IP,如代理支持此功能取到的还是代理IP,注意:如用户没用代理取到的是空值""

环境变量变量值
ALL_HTTPHTTP_CONNECTION:Keep-Alive HTTP_ACCEPT:image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* HTTP_ACCEPT_ENCODING:gzip, deflate HTTP_ACCEPT_LANGUAGE:zh-cn HTTP_COOKIE:ASP.NET_SessionId=5dchvi3oayuayd55zlrx35av HTTP_HOST:localhost HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
ALL_RAWConnection: Keep-Alive Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* Accept-Encoding: gzip, deflate Accept-Language: zh-cn Cookie: ASP.NET_SessionId=5dchvi3oayuayd55zlrx35av Host: localhost User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
APPL_MD_PATH/LM/w3svc/1/root/Temp/WebApp
APPL_PHYSICAL_PATHc:\inetpub\wwwroot\Temp\WebApp\
AUTH_TYPE
AUTH_USER
AUTH_PASSWORD
LOGON_USER
REMOTE_USER
CERT_COOKIE
CERT_FLAGS
CERT_ISSUER
CERT_KEYSIZE
CERT_SECRETKEYSIZE
CERT_SERIALNUMBER
CERT_SERVER_ISSUER
CERT_SERVER_SUBJECT
CERT_SUBJECT
CONTENT_LENGTH0
CONTENT_TYPE
GATEWAY_INTERFACECGI/1.1
HTTPSoff
HTTPS_KEYSIZE
HTTPS_SECRETKEYSIZE
HTTPS_SERVER_ISSUER
HTTPS_SERVER_SUBJECT
INSTANCE_ID1
INSTANCE_META_PATH/LM/W3SVC/1
LOCAL_ADDR127.0.0.1
PATH_INFO/Temp/WebApp/ServerVariables.aspx
PATH_TRANSLATEDc:\inetpub\wwwroot\Temp\WebApp\ServerVariables.aspx
QUERY_STRING
REMOTE_ADDR127.0.0.1
REMOTE_HOST127.0.0.1
REMOTE_PORT4529
REQUEST_METHODGET
SCRIPT_NAME/Temp/WebApp/ServerVariables.aspx
SERVER_NAMElocalhost
SERVER_PORT80
SERVER_PORT_SECURE0
SERVER_PROTOCOLHTTP/1.1
SERVER_SOFTWAREMicrosoft-IIS/5.0
URL/Temp/WebApp/ServerVariables.aspx
HTTP_CONNECTIONKeep-Alive
HTTP_ACCEPTimage/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
HTTP_ACCEPT_ENCODINGgzip, deflate
HTTP_ACCEPT_LANGUAGEzh-cn
HTTP_COOKIEASP.NET_SessionId=5dchvi3oayuayd55zlrx35av
HTTP_HOSTlocalhost
HTTP_USER_AGENTMozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
[/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: