一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

asp.net C#类型转换的示例

时间:2014-08-28 编辑:简简单单 来源:一聚教程网

1.任何一门编程语言均有相关数据类型。C#也不例外,其基本数据类型有int,short,long,float,double,string等。数据类型之间可以相互转换。不过转换过程要注意小类型能转换成大类型,但大类型一般不能转换成小类型。如int型可以转换成float型,但float型不一定可以转换成int型,至少这在C,C++是这样,但在C#中明显有了改变,似乎微软公司也允许这样的形式存在了。例如:

 代码如下 复制代码

double dbl_num=12345678910.456;
int k = (int) dbl_num ;//此处运用了强制转换

以上代码如果在C,C++中强制转换成int型,肯定会出错,但现在在C#中却不会出错了,不过转换后的值往往是溢出值,是不精通的。这点需要大家注意。

 2.采用另一种方式转换类型,如int.parse(),int32.parse()等采用方法来转换.

 代码如下 复制代码

如string str=”100〃;

int i=int.Parse(str);

注意:str除掉引号的类型必须和*.Parse的类型一致。如果将100改成100.78,即变成float类型,运行时将会报错”输入字符串的格式不正确.”

 3.采用后缀式转换,如k.toString(),一般运用于字符串或日期等其它类型

 代码如下 复制代码

int i=100;

string s=i.ToString();

 4.采用Convert类来实现转换,该类基本支持所以类型之间的转换

 代码如下 复制代码

string   str=”100〃;

int   i = Convert.ToInt16(str);

注意:str除掉引号的类型必须和Convert.*的类型一致。如果将100改成100.78,即变成float类型,运行时将会报错”输入字符串的格式不正确.”

例子

 代码如下 复制代码

using System;
class TypeTrans
{
 public static void Main( )
 {
  //隐式转换,int到long 和 float到double
  Console.WriteLine("隐式转换:");
  int iValue = int.MaxValue;
  long lValue = iValue;  //转换成功
  Console.WriteLine("int {0} -> long {1}", iValue, lValue);
  float fValue = float.MaxValue;
  double dValue = fValue;  //转换成功,但数字精度可能会有影响
  Console.WriteLine("float {0} -> double {1}", fValue, dValue);
  //float fValue2 = dValue;     不允许隐式转换,会导致编译错误
  //显示转换
  Console.WriteLine("显示转换:");
  int iValue2 = (int) lValue; //long变量的值在int表示范围内,转换成功
  Console.WriteLine("long {0} -> int {1}", lValue, iValue2);
  lValue = lValue + 1;
  int iValue3 = (int) lValue; //long变量值超出int表示范围,转换不成功
  Console.WriteLine("long {0} -> int {1}", lValue, iValue3);
  //C#中提供的显示转换溢出检查机制
  Console.WriteLine("不使用溢出检查的溢出转换:");
  byte bValue = (byte) iValue;
  Console.WriteLine("int {0} -> byte {1}", iValue, bValue);
  Console.WriteLine("使用溢出检查后的溢出转换:");
  byte bValue2 = checked ( (byte) iValue ); //这里会抛出异常
 }
}

最后再看一个更完整类型转换例子

 代码如下 复制代码

//各种数据类型转换方法的类
    public class GF_Convert
    {
///


/// 字符串 转换 char数组
///

///
///
///
public static char[] string2chararray(string in_str, int in_len)
{
    char[] ch = new char[in_len];
    in_str.ToCharArray().CopyTo(ch, 0);
    return ch;
}

///


/// char数组 转换 字符串
///

///
///
public static string chararray2string(char[] in_str)
{
    string out_str;
    out_str = new string(in_str);
    int i = out_str.IndexOf('', 0);
    if (i == -1)
i = 16;
    return out_str.Substring(0, i);
}

///


/// byte数组 转换 字符串
///

///
///
public static string bytearray2string(byte[] in_str)
{
    string out_str;
    out_str = System.Text.Encoding.Default.GetString(in_str);
    return out_str.Substring(0, out_str.IndexOf('', 0));

}

///


/// 字符串 转换 byte数组  注意转换出来会使原来的bytearray长度变短
///

///
///
public static byte[] string2bytearray(string in_str)
{
    return System.Text.Encoding.Default.GetBytes(in_str);
}

///


/// 字符串 转换 byte数组  长度为传如的长度
///

/// 传入字符串
/// 目标字节数组长度
///
public static byte[] string2bytearray(string in_str, int iLen)
{
    byte[] bytes = new byte[iLen];
    byte[] bsources=System.Text.Encoding.Default.GetBytes(in_str);
    Array.Copy(bsources, bytes, bsources.Length);
   
   
    return bytes;
}

///


/// 将字符串编码为Base64字符串
///

///
///
public static string Base64Encode(string str)
{
    byte[] barray;
    barray = Encoding.Default.GetBytes(str);
    return Convert.ToBase64String(barray);
}

///


/// 将Base64字符串解码为普通字符串
///

///
///
public static string Base64Decode(string str)
{
    byte[] barray;
    try
    {
barray = Convert.FromBase64String(str);
return Encoding.Default.GetString(barray);
    }
    catch
    {
return str;
    }
}

///


/// 图片 转换 byte数组
///

///
///
///
public static byte[] image_Image2Byte(Image pic, System.Drawing.Imaging.ImageFormat fmt)
{
    MemoryStream mem = new MemoryStream();
    pic.Save(mem, fmt);
    mem.Flush();
    return mem.ToArray();
}
///
/// byte数组 转换 图片
///

///
///
public static Image image_Byte2Image(byte[] bytes)
{
    MemoryStream mem = new MemoryStream(bytes, true);
    mem.Read(bytes, 0, bytes.Length);
    mem.Flush();
    Image aa = Image.FromStream(mem);
    return aa;
}

///


/// ip 转换 长整形
///

///
///
public static long IP2Long(string strIP)
{

    long[] ip = new long[4];

    string[] s = strIP.Split('.');
    ip[0] = long.Parse(s[0]);
    ip[1] = long.Parse(s[1]);
    ip[2] = long.Parse(s[2]);
    ip[3] = long.Parse(s[3]);

    return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
}

///


/// 长整形 转换 IP
///

///
///
public static string Long2IP(long longIP)
{


    StringBuilder sb = new StringBuilder("");
    sb.Append(longIP >> 24);
    sb.Append(".");

    //将高8位置0,然后右移16为


    sb.Append((longIP & 0x00FFFFFF) >> 16);
    sb.Append(".");


    sb.Append((longIP & 0x0000FFFF) >> 8);
    sb.Append(".");

    sb.Append((longIP & 0x000000FF));


    return sb.ToString();
}

///


/// 将8位日期型整型数据转换为日期字符串数据
///

/// 整型日期
/// 是否以中文年月日输出
///
public static string FormatDate(int date, bool chnType)
{
    string dateStr = date.ToString();

    if (date <= 0 || dateStr.Length != 8)
return dateStr;

    if (chnType)
return dateStr.Substring(0, 4) + "年" + dateStr.Substring(4, 2) + "月" + dateStr.Substring(6) + "日";

    return dateStr.Substring(0, 4) + "-" + dateStr.Substring(4, 2) + "-" + dateStr.Substring(6);
}


///


/// string型转换为bool型
///

/// 要转换的字符串
/// 缺省值
/// 转换后的bool类型结果
public static bool StrToBool(object expression, bool defValue)
{
    if (expression != null)
return StrToBool(expression, defValue);

    return defValue;
}

///


/// string型转换为bool型
///

/// 要转换的字符串
/// 缺省值
/// 转换后的bool类型结果
public static bool StrToBool(string expression, bool defValue)
{
    if (expression != null)
    {
if (string.Compare(expression, "true", true) == 0)
    return true;
else if (string.Compare(expression, "false", true) == 0)
    return false;
    }
    return defValue;
}

///


/// 将对象转换为Int32类型
///

/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static int ObjectToInt(object expression)
{
    return ObjectToInt(expression, 0);
}

///


/// 将对象转换为Int32类型
///

/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static int ObjectToInt(object expression, int defValue)
{
    if (expression != null)
return StrToInt(expression.ToString(), defValue);

    return defValue;
}

///


/// 将对象转换为Int32类型,转换失败返回0
///

/// 要转换的字符串
/// 转换后的int类型结果
public static int StrToInt(string str)
{
    return StrToInt(str, 0);
}

///


/// 将对象转换为Int32类型
///

/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static int StrToInt(string str, int defValue)
{
    if (string.IsNullOrEmpty(str) || str.Trim().Length >= 11 || !Regex.IsMatch(str.Trim(), @"^([-]|[0-9])[0-9]*(.w*)?$"))
return defValue;

    int rv;
    if (Int32.TryParse(str, out rv))
return rv;

    return Convert.ToInt32(StrToFloat(str, defValue));
}

///


/// string型转换为float型
///

/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static float StrToFloat(object strValue, float defValue)
{
    if ((strValue == null))
return defValue;

    return StrToFloat(strValue.ToString(), defValue);
}

///


/// string型转换为float型
///

/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static float ObjectToFloat(object strValue, float defValue)
{
    if ((strValue == null))
return defValue;

    return StrToFloat(strValue.ToString(), defValue);
}

///


/// string型转换为float型
///

/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static float ObjectToFloat(object strValue)
{
    return ObjectToFloat(strValue.ToString(), 0);
}

///


/// string型转换为float型
///

/// 要转换的字符串
/// 转换后的int类型结果
public static float StrToFloat(string strValue)
{
    if ((strValue == null))
return 0;

    return StrToFloat(strValue.ToString(), 0);
}

///


/// string型转换为float型
///

/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static float StrToFloat(string strValue, float defValue)
{
    if ((strValue == null) || (strValue.Length > 10))
return defValue;

    float intValue = defValue;
    if (strValue != null)
    {
bool IsFloat = Regex.IsMatch(strValue, @"^([-]|[0-9])[0-9]*(.w*)?$");
if (IsFloat)
    float.TryParse(strValue, out intValue);
    }
    return intValue;
}

///


/// 将对象转换为日期时间类型
///

/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static DateTime StrToDateTime(string str, DateTime defValue)
{
    if (!string.IsNullOrEmpty(str))
    {
DateTime dateTime;
if (DateTime.TryParse(str, out dateTime))
    return dateTime;
    }
    return defValue;
}

///


/// 将对象转换为日期时间类型
///

/// 要转换的字符串
/// 转换后的int类型结果
public static DateTime StrToDateTime(string str)
{
    return StrToDateTime(str, DateTime.Now);
}

///


/// 将对象转换为日期时间类型
///

/// 要转换的对象
/// 转换后的int类型结果
public static DateTime ObjectToDateTime(object obj)
{
    return StrToDateTime(obj.ToString());
}

///


/// 将对象转换为日期时间类型
///

/// 要转换的对象
/// 缺省值
/// 转换后的int类型结果
public static DateTime ObjectToDateTime(object obj, DateTime defValue)
{
    return StrToDateTime(obj.ToString(), defValue);
}

///


/// 替换回车换行符为html换行符
///

public static string StrFormat(string str)
{
    string str2;

    if (str == null)
    {
str2 = "";
    }
    else
    {
str = str.Replace("rn", "
");
str = str.Replace("n", "
");
str2 = str;
    }
    return str2;
}

///


/// 转换为简体中文
///

public static string ToSChinese(string str)
{
    return Strings.StrConv(str, VbStrConv.SimplifiedChinese, 0);
   
}

///


/// 转换为繁体中文
///

public static string ToTChinese(string str)
{
    return Strings.StrConv(str, VbStrConv.TraditionalChinese, 0);
   
}


///


/// 清除字符串数组中的重复项
///

/// 字符串数组
/// 字符串数组中单个元素的最大长度
///
public static string[] DistinctStringArray(string[] strArray, int maxElementLength)
{
    Hashtable h = new Hashtable();

    foreach (string s in strArray)
    {
string k = s;
if (maxElementLength > 0 && k.Length > maxElementLength)
{
    k = k.Substring(0, maxElementLength);
}
h[k.Trim()] = s;
    }

    string[] result = new string[h.Count];

    h.Keys.CopyTo(result, 0);

    return result;
}

///


/// 清除字符串数组中的重复项
///

/// 字符串数组
///
public static string[] DistinctStringArray(string[] strArray)
{
    return DistinctStringArray(strArray, 0);
}

}

热门栏目