explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符

本文介绍了C#中explicit关键字的应用,通过示例展示了如何在Fahrenheit和Celsius两个类之间进行显式类型转换。此类转换需要程序员明确指定,以避免意外的数据类型变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符。例如,在下面的示例中,此运算符将名为 Fahrenheit 的类转换为名为 Celsius 的类:

// Must be defined inside a class called Farenheit:
public static explicit operator Celsius(Farenheit f)
{
    
return new Celsius((5.0f/9.0f)*(f.degrees-32));
}

可以如下所示调用此转换运算符:
Farenheit f = new Farenheit(100.0f);
Celsius c 
= (Celsius)f;
下面的示例提供 FahrenheitCelsius 类,它们中的每一个都为另一个提供显式转换运算符。
// 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);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值