在C#中,变量转换通常指将一个变量从一种类型转换为另一种类型。这可以通过以下几种方式实现:
1隐式转换(隐式转换是安全的,不会导致数据丢失):
int a = 10;
double b = a; // a 隐式转换为 double 类型
2显式转换(显式转换可能导致数据丢失或引发异常,需要使用强制转换运算符):
double c = 10.5;
int d = (int)c; // c 显式转换为 int 类型,可能会丢失小数部分
3使用Convert类进行转换(Convert类提供了一组静态方法用于转换类型,但它不是隐式或显式转换):
double e = 10.5;
int f = Convert.ToInt32(e); // Convert.ToInt32 将 double 转换为 int,但不推荐用于性能关键代码
4使用as
关键字进行安全转换(as
关键字用于引用类型的转换,并且如果转换不成功不会抛出异常,而是返回null):
object g = 10;
int? h = g as int?; // 安全转换 object 到 int?,如果转换失败则返回 null
5使用is
关键字检查类型是否可以转换(is
用于检查对象是否可以转换为指定的类型,不会进行实际转换):
object i = 10;
bool isInt = i is int; // 检查 i 是否可以转换为 int 类型
6自定义转换(使用转换运算符重载自定义类型之间的转换):
public class CustomType
{
public int Value { get; set; }
// 定义隐式转换到 int
public static implicit operator int(CustomType custom)
{
return custom.Value;
}
// 定义显式转换从 int
public static explicit operator CustomType(int value)
{
return new CustomType { Value = value };
}
}
CustomType j = new CustomType { Value = 10 };
int k = j; // 使用自定义隐式转换
CustomType l = (CustomType)k; // 使用自定义显式转换