【随笔】C#中的 explicit和implicit 关键字

在学习Unity的Playable功能时翻阅代码发现有这么两个函数,遂查阅了一些资料,并记录了下来。
【随笔】C#中的 explicit和implicit 关键字_第1张图片

用户定义转换运算符

用户定义类型可以定义从或到另一个类型的自定义隐式或显式转换。

隐式转换无需调用特殊语法,并且可以在各种情况(例如,在赋值和方法调用中)下发生。 预定义的 C# 隐式转换始终成功,且永远不会引发异常。 用户定义隐式转换也应如此。 如果自定义转换可能会引发异常或丢失信息,请将其定义为显式转换。

//这是个Playable实际开发中的例子
m_AdapterPlayable = ScriptPlayable<AnimAdapter>.Create(graph);
((ScriptPlayable<AnimAdapter>)m_AdapterPlayable).GetBehaviour().Init(this);

object o = "test";
string s = (string)o;

short shortV = 100;
int intV = shortV + 1;

is 和 as 运算符不考虑使用用户定义转换。 强制转换表达式用于调用用户定义显式转换。

bool b1 = gameObject is GameObject;

UnityEngine.Object o1 = new UnityEngine.Object();
GameObject o2 = o1 as GameObject;

operator 和 implicit 或 explicit 关键字分别用于定义隐式转换或显式转换。 定义转换的类型必须是该转换的源类型或目标类型。 可用两种类型中的任何一种类型来定义两种用户定义类型之间的转换。

using System;

public readonly struct Digit
{
    private readonly byte digit;

    public Digit(byte digit)
    {
        if (digit > 9)
        {
            throw new ArgumentOutOfRangeException(nameof(digit), "Digit cannot be greater than nine.");
        }
        this.digit = digit;
    }

    public static implicit operator byte(Digit d) => d.digit;
    public static explicit operator Digit(byte b) => new Digit(b);

    public override string ToString() => $"{digit}";
}

public static class UserDefinedConversions
{
    public static void Main()
    {
        var d = new Digit(7);

        byte number = d;
        Console.WriteLine(number);  // output: 7

        Digit digit = (Digit)number;
        Console.WriteLine(digit);  // output: 7
    }
}

参考:https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/operators/user-defined-conversion-operators

你可能感兴趣的:(c#,unity)