c 資料型別轉換

2021-08-21 15:35:17 字數 1919 閱讀 6260

隱式型別轉換-

這些轉換是 c# 預設的以安全方式進行的轉換, 不會導致資料丟失。例如,從小的整數型別轉換為大的整數型別,從派生類轉換為基類。

轉換規則
從儲存範圍小的型別到儲存範圍大的型別。
整數具體規則為:
byte→short(char)→int→long→float→double
也就是說byte型別的變數可以自動轉換為short型別,示例**:
byte b = 10;
short sh = b;
在型別轉換時可以跳躍。示例**:
byte b1 = 100;
int n = b1;
顯式型別轉換-

顯式型別轉換,即強制型別轉換。顯式轉換需要強制轉換運算子,而且強制轉換會造成資料丟失。

轉換規則
從儲存範圍大的型別到儲存範圍小的型別。
具體規則為:
double→float→long→int→short(char)→byte
例如:
double d = 5673.74;
int i;
i = (int)d;
1.  convert.toint32()       2.  int.parse()

convert.toint32()則可以將多種型別(包括

object  

引用型別

)的值轉換為

int  型別,

因為它有許多過載版本

[2]:

public static int toint32(object);

public static int toint32(bool);

public static int toint32(byte);

public static int toint32(char);

public static int toint32(decimal);

public static int toint32(double);

public static int toint32(short);

public static int toint32(long);

public static int toint32(sbyte);

public static int toint32(string);

int32.parse()表示將包含數字的字串轉換為

32 位有符號整數,屬於內容轉換 如果

string

為空,則丟擲

argumentnullexception

異常;如果

string

格式不正確,則丟擲

formatexception

異常;

可以看出來,convert.toint32()的功能是最強大的,它把int32.parse()功能包括了,也是說是int32.parse()convert.toint32()的一種特殊情況。

C 資料型別轉換

轉cstring cstring.format t d int 轉char 1.itoa int,char 10 10為十進位制 沒有越界檢查 2.memset szbuf,0,sizeof szbuf snprintf szbuf,sizeof szbuf d int 轉tchar itoa in...

C 資料型別轉換

include include using namespace std 從型別t轉換為型別k template classt,class k k convert t tmp intmain home hejinyang clion2016.2 system cmake generated mypro...

C 資料型別轉換

一 隱式資料型別轉換 由編譯器自動去轉換型別,比如byte型別轉換為int型別 int i 12 byte j 125 i j console.writeline i 125 請按任意鍵繼續.隱式型別轉換的條件 1 資料型別是相容的 2 目標型別一定要大於原型別 二 強制資料型別轉換 有可能造成資料...