C#学习笔记 -- 自定义类型转换

定义的类型转换

  • 可以位自己的类和结构定义隐式转换和显式转换, 这里允许把用户定义类型的对象转换成某个其他类型, 反之亦然

  • 隐式转换与显式转换

    • 对于转换, 当决定在特定上下文中使用特定类型时, 如有必要, 编译器会自动执行转换

    • 对于显式转换, 编译器只在使用显式转换运算符时才执行转换

(1)隐式转换

  • 转换的方法必须是public static

  • implicit隐式转换

public static implicit operator 目标类型(原数据类型 形参)
{
    ...
    return 目标类型返回值;
}
例子
class LimitedInt
{
    const int MaxValue = 100;
    const int MinValue = 0;
​
    private int theValue = 0;
    public int TheValue
    {
        set
        {
            if (value < MinValue)
            {
                theValue = MinValue;
            }
            else
            {
                theValue = value > MaxValue ? MaxValue : value;
            }
        }
        get { return theValue; }
    }
​
    public LimitedInt(int theValue)
    {
        TheValue = theValue;
    }
​
    public LimitedInt()
    {
    }
​
    //隐式转换  自定义类型转换 => int
    public static implicit operator int(LimitedInt li)
    {
        return li.TheValue;
    }
    //隐式转换 int => 自定义类型转换
    public static implicit operator LimitedInt(int i)
    {
        return new LimitedInt(i);
    }
}
static void Main(string[] args)
{
    //914 limitedInt
    {
        //隐式的转换为自定义类型
        LimitedInt limitedInt = 500;
        int i = limitedInt;
        Console.WriteLine($"自定义类型值为{limitedInt.TheValue}, int类型值为{i}"); //100 100
    }
}

(2)显式转换与强制转换运算符

  • 转换的方法必须是public static

  • explicit隐式转换

  • 强制转换符 目标类型 var1 = (目标类型) var2

  • 必须配上强制转换运算符使用, 代表不得不实行转换时候进行转换类型

public static explicit operator 目标类型(原数据类型 形参)
{
    ...
    return 目标类型返回值;
}
例子
class LimitedInt
{
    const int MaxValue = 100;
    const int MinValue = 0;
​
    private int theValue = 0;
    public int TheValue
    {
        set
        {
            if (value < MinValue)
            {
                theValue = MinValue;
            }
            else
            {
                theValue = value > MaxValue ? MaxValue : value;
            }
        }
        get { return theValue; }
    }
​
    public LimitedInt(int theValue)
    {
        TheValue = theValue;
    }
​
    public LimitedInt()
    {
    }
​
    //显式转换  自定义类型转换 => int
    public static explicit operator int(LimitedInt li)
    {
        return li.TheValue;
    }
    //显式转换 int => 自定义类型转换
    public static explicit operator LimitedInt(int i)
    {
        return new LimitedInt(i);
    }
}
static void Main(string[] args)
{
    //914 limitedInt
    {
        //隐式的转换为自定义类型
        LimitedInt limitedInt = (LimitedInt)500;
        int i = (int) limitedInt;
        Console.WriteLine($"自定义类型值为{limitedInt.TheValue}, int类型值为{i}"); //100 100
    }
}
注意
  • 还有两个运算符接受一种类型的值, 并返回另一种不同的, 指定类型的值, is as

posted on 2023-05-23 23:08  老菜农  阅读(89)  评论(0编辑  收藏  举报

导航