关于implicit和explicit关键词的用法

本文介绍 C# 中 explicit 和 implicit 关键字的使用方法,详细解释了如何声明显式和隐式类型转换运算符,并通过示例说明了何时应该使用这两种关键字。

关于implicit和explicit关键词的用法

explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符。
//  cs_keyword_explicit_temp.cs
using  System;
class  Celsius
{
    
public Celsius(float temp)
    
{
        degrees 
= temp;
    }

    
public static explicit operator Fahrenheit(Celsius c)
    
{
        
return new Fahrenheit((9.0f / 5.0f* c.degrees + 32);
    }

    
public float Degrees
    
{
        
get return degrees; }
    }

    
private float degrees;
}


class  Fahrenheit
{
    
public Fahrenheit(float temp)
    
{
        degrees 
= temp;
    }

    
public static explicit operator Celsius(Fahrenheit f)
    
{
        
return new Celsius((5.0f / 9.0f* (f.degrees - 32));
    }

    
public float Degrees
    
{
        
get return degrees; }
    }

    
private float degrees;
}


class  MainClass
{
    
static void Main()
    
{
        Fahrenheit f 
= new Fahrenheit(100.0f);
        Console.Write(
"{0} fahrenheit", f.Degrees);
        Celsius c 
= (Celsius)f;
        Console.Write(
" = {0} celsius", c.Degrees);
        Fahrenheit f2 
= (Fahrenheit)c;
        Console.WriteLine(
" = {0} fahrenheit", f2.Degrees);
    }

}

转换运算符将源类型转换为目标类型。源类型提供转换运算符。 与隐式转换不同,必须通过强制转换的方式来调用显式转换运算符。
如果转换操作可能导致异常或丢失信息,则应将其标记为 explicit。这可以防止编译器无提示地调用可能产生无法预见后果的转换操作。

implicit 关键字用于声明隐式的用户定义类型转换运算符。
static implicit operator target_type { source_type identifier }
   
class  MyType 
{
    
public static implicit operator int(MyType m) 
    
{
        
// code to convert from MyType to int
    }

}

MyType x;
//  implicitly call MyType's MyType-to-int conversion operator
int  i  =  x;
隐式转换可以通过消除不必要的类型转换来提高源代码的可读性。但是,因为可以在程序员未指定的情况下发生隐式转换,因此必须注意防止令人不愉快的
后果。一般情况下,隐式转换运算符应当从不引发异常并且从不丢失信息,以便可以在程序员不知晓的情况下安全使用它们。如果转换运算符不能满足那些
条件,则应将其标记为 explicit
作者: Jackhuclan
出处: http://jackhuclan.cnblogs.com/ 
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
在 C# 编程语言中,关键字是预定义的保留标识符,具有特殊的编译器含义。这些关键字不能直接用作变量名、方法名或其他用户定义的标识符,除非在其前面加上 `@` 前缀。例如,`if` 是一个关键字,不能作为标识符使用,但 `@if` 可以[^1]。 ### C# 关键字列表 C# 中的关键字可以分为两类:**保留关键字****上下文关键字**。 #### 保留关键字 保留关键字在程序中的任何地方都有特殊意义,并且始终被编译器视为关键字。以下是一些常见的保留关键字: - `abstract` - `as` - `base` - `bool` - `break` - `byte` - `case` - `catch` - `char` - `checked` - `class` - `const` - `continue` - `decimal` - `default` - `delegate` - `do` - `double` - `else` - `enum` - `event` - `explicit` - `extern` - `false` - `finally` - `fixed` - `float` - `for` - `foreach` - `goto` - `if` - `implicit` - `in` - `int` - `interface` - `internal` - `is` - `lock` - `long` - `namespace` - `new` - `null` - `object` - `operator` - `out` - `override` - `params` - `private` - `protected` - `public` - `readonly` - `ref` - `return` - `sbyte` - `sealed` - `short` - `sizeof` - `stackalloc` - `static` - `string` - `struct` - `switch` - `this` - `throw` - `true` - `try` - `typeof` - `uint` - `ulong` - `unchecked` - `unsafe` - `ushort` - `using` - `virtual` - `void` - `volatile` - `while` #### 上下文关键字 上下文关键字仅在特定代码结构中有特殊含义,可以在其他上下文中用作标识符。例如,`get` `set` 在属性定义中是关键字,但在其他地方可以作为变量名使用。常见上下文关键字包括: - `add` - `alias` - `ascending` - `async` - `await` - `by` - `descending` - `dynamic` - `equals` - `from` - `get` - `global` - `group` - `into` - `join` - `let` - `nameof` - `on` - `orderby` - `partial` - `remove` - `select` - `set` - `value` - `var` - `when` - `where` - `yield` ### C# 常用函数概述 C# 中的“函数”通常被称为方法(Methods),它们封装了可重用的逻辑。以下是一些常用的内置函数类库方法: #### 数学运算 ```csharp Math.Abs(-5); // 返回绝对值 Math.Sqrt(16); // 计算平方根 Math.Round(3.7); // 四舍五入 ``` #### 字符串处理 ```csharp string.IsNullOrEmpty("test"); // 检查字符串是否为空或 null str.ToUpper(); // 将字符串转换为大写 str.Substring(0, 3); // 获取子字符串 ``` #### 类型转换 ```csharp int.Parse("123"); // 将字符串转换为整数 Convert.ToDouble("45.6"); // 转换为双精度浮点数 ``` #### 集合操作 ```csharp List<int> numbers = new List<int>(); numbers.Add(10); // 添加元素 numbers.Contains(10); // 判断是否存在某元素 numbers.Sort(); // 对集合排序 ``` #### 异常处理 ```csharp try { // 可能抛出异常的代码 } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { // 清理资源 } ``` #### 文件操作 ```csharp File.WriteAllText("file.txt", "Hello World"); // 写入文件 string content = File.ReadAllText("file.txt"); // 读取文件内容 ``` #### LINQ 查询 ```csharp var result = from num in numbers where num > 5 select num; ``` LINQ 提供了一种类似于 SQL 的语法来查询数据源,支持从数组、列表、数据库等来源提取数据。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值