1.C++ 数据类型转化
在C++中,可以使用类型转换运算符或者类型转换函数来进行数据类型之间的转化。以下是一些常见数据类型之间的转化示例代码:
1.整数类型之间的转化:
int a = 10;
double b = static_cast<double>(a); // 将整数转换为双精度浮点数
2.指针类型之间的转化:
int* ptr = new int(5);
uintptr_t uintptr = reinterpret_cast<uintptr_t>(ptr); // 将指针转换为整数
int* newPtr = reinterpret_cast<int*>(uintptr); // 将整数转换为指针
3.字符串类型之间的转化:
#include <string>
#include <sstream>
// string 转 int
std::string str = "123";
int num;
std::istringstream(str) >> num;
// int 转 string
int number = 123;
std::string str = std::to_string(number);
4.枚举类型之间的转化:
enum class MyEnum { A, B, C };
int enumValue = static_cast<int>(MyEnum::A); // 将枚举值转换为整数
MyEnum myEnum = static_cast<MyEnum>(2); // 将整数转换为枚举值
5.自定义类型之间的转化:
class A {
public:
A(int x) : value(x) {}
operator int() const { return value; } // 自定义类型到整数的转化
private:
int value;
};
int main() {
A a(10);
int x = a;
return 0;
}
2.C# 数据类型间互相转化
在 C# 中,可以使用各种方法进行数据类型之间的相互转换。以下是一些常见数据类型之间的转换示例代码:
1.整数类型之间的转换:
int a = 10;
double b = Convert.ToDouble(a); // 将整数转换为双精度浮点数
2.字符串类型之间的转换:
// 字符串转换为整数
string str = "123";
int num = Convert.ToInt32(str);
// 整数转换为字符串
int number = 123;
string str = number.ToString();
3.枚举类型之间的转换:
public enum MyEnum { A, B, C }
int enumValue = (int)MyEnum.A; // 将枚举值转换为整数
MyEnum myEnum = (MyEnum)2; // 将整数转换为枚举值
4.日期类型之间的转换:
DateTime now = DateTime.Now;
string dateString = now.ToString("yyyy-MM-dd"); // DateTime 转换为字符串
DateTime date = DateTime.Parse("2024-03-25"); // 字符串转换为 DateTime
5.自定义类型之间的转换:
public class MyClass
{
public int Value { get; set; }
public static implicit operator int(MyClass myClass)
{
return myClass.Value;
}
public static explicit operator MyClass(int value)
{
return new MyClass { Value = value };
}
}
// 使用自定义类型转换
MyClass myObject = new MyClass { Value = 10 };
int x = myObject; // 调用 implicit 转换操作符
MyClass myNewObject = (MyClass)20; // 调用 explicit 转换操作符