is运算符用于类型检查,返回布尔值;as运算符尝试转换类型,失败返回null。两者均不抛异常,is适用于条件判断,as适用于安全转换。

C#中
is
as
null
as
is
as
is
is
true
false
is
例如:
object obj = "Hello";
if (obj is string)
{
Console.WriteLine("obj is a string.");
}as
as
null
as
例如:
object obj = "Hello";
string str = obj as string;
if (str != null)
{
Console.WriteLine("Conversion successful: " + str);
}
else
{
Console.WriteLine("Conversion failed.");
}区别总结
| 特性 | @@######@@ 运算符 | @@######@@ 运算符 |
|---|---|---|
| 返回值 | @@######@@ (true 或 false) | 转换后的对象引用或 @@######@@ |
| 转换 | 不执行转换 | 尝试执行转换 |
| 异常 | 不抛出异常 | 不抛出异常 |
| 适用类型 | 所有类型 | 引用类型和可空类型 |
| 用途 | 类型检查 | 类型转换和类型检查 |
类型转换方式
除了
is
as
强制类型转换(Casting)
强制类型转换使用圆括号
bool
null
is
使用 as
()
InvalidCastException
使用 double d = 123.45;
int i = (int)d; // 强制将 double 转换为 int
某些类型(例如
Convert
Convert
double d = 123.45; int i = Convert.ToInt32(d); // 使用 Convert 类将 double 转换为 int
TryParse
int
double
TryParse
TryParse
out
TryParse
string str = "123";
int i;
if (int.TryParse(str, out i))
{
Console.WriteLine("Conversion successful: " + i);
}
else
{
Console.WriteLine("Conversion failed.");
}is
is
is
ArrayList list = new ArrayList() { "Hello", 123, true };
foreach (object obj in list)
{
if (obj is string)
{
string str = (string)obj; // 确定是字符串后才进行强制转换
Console.WriteLine("String: " + str);
}
}选择合适的类型转换方式取决于具体的场景和需求。
as
as
as
object obj = "Hello";
string str = obj as string;
if (str != null)
{
Console.WriteLine("String: " + str);
}
else
{
Console.WriteLine("Not a string.");
}总而言之,
is
as
TryParse
Convert
is
as
以上就是C#的is运算符和as运算符有什么区别?如何转换类型?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号