c# 自定义隐式转换与运算符重载

news2024/9/26 5:15:05

用户定义的显式和隐式转换运算符

参考代码

用户定义的显式和隐式转换运算符 - 提供对不同类型的转换 | Microsoft Learn

代码例程

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
    }
}

自实现 隐式运算符转换例程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    class Person
    {
        public string Name { get; set; }
        public int age { get; set; }
        public Person(string name, int age)
        {
            Name = name;
            this.age = age;
        }

        /// <summary>
        /// 自定义隐式转换
        /// </summary>
        /// <param name="p"></param>
        public static  implicit operator string (Person p)
        {
            return p.Name;
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person("张三",20);
            Person p2 = new Person("李四", 30);
            string username = p1 + p2; //自定义对象隐式转换
            Console.WriteLine(username);
            Console.ReadLine();
        }
    }
}

运行结果

上面当然也可以适用于年龄,只需要修改返回值即可。

自实现 显式运算符转换例程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp7
{
    class Person
    {
        public string Name { get; set; }
        public int age { get; set; }
        public Person(string name, int age)
        {
            Name = name;
            this.age = age;
        }

        /// <summary>
        /// 自定义隐式转换
        /// </summary>
        /// <param name="p"></param>
        //public static implicit operator string(Person p)
        //{
        //    return p.Name;
        //}

        //public static implicit operator Person(string name)
        //{
        //    return new Person(name, 0);
        //}
       
        ///运算符重载
        public static string operator +(Person p1, Person p2)
        {
            return p1.Name + p2.Name; 
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person("张三", 20);
            Person p2 = new Person("李四", 30);
            //string username = p1 + p2; //自定义对象隐式转换
            //Console.WriteLine(username);

            //Person p3 = "王五"; //强转,与视频中不同的时前面没有加括号
            //Person p3a = (Person)"赵六"; //视频中加了括号强转
            //Console.WriteLine(p3.Name + " " + p3.age.ToString());
            //Console.WriteLine(p3a.Name + " " + p3a.age.ToString());

            string username = p1 + p2; //自定义对象 + 重载
            Console.WriteLine(username);

            Console.ReadLine();
        }
    }
}

运行结果

与上面的相同,注意这里时显式运算符重载。

 

强制类型转换

自定义对象强转转换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp6
{
    class Person
    {
        public string Name { get; set; }
        public int age { get; set; }
        public Person(string name, int age)
        {
            Name = name;
            this.age = age;
        }

        /// <summary>
        /// 自定义隐式转换
        /// </summary>
        /// <param name="p"></param>
        //public static implicit operator string(Person p)
        //{
        //    return p.Name;
        //}

        public static implicit operator Person(string name)
        {
            return new Person(name, 0);
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person("张三", 20);
            Person p2 = new Person("李四", 30);
            //string username = p1 + p2; //自定义对象隐式转换
            //Console.WriteLine(username);

            Person p3 = "王五"; //强转,与视频中不同的时前面没有加括号
            Person p3a = (Person)"赵六"; //视频中加了括号强转

            Console.WriteLine(p3.Name + " " + p3.age.ToString());
            Console.WriteLine(p3a.Name + " " + p3a.age.ToString());


            Console.ReadLine();
        }
    }
}

运行结果(注意没有初始化年龄,使用默认)

+运算符重载

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    class Person
    {
        public string Name { get; set; }
        public int age { get; set; }
        public Person(string name, int age)
        {
            Name = name;
            this.age = age;
        }

        /// <summary>
        /// 自定义隐式转换
        /// </summary>
        /// <param name="p"></param>
        //public static implicit operator string(Person p)
        //{
        //    return p.Name;
        //}

        //public static implicit operator Person(string name)
        //{
        //    return new Person(name, 0);
        //}

        ///运算符重载
        public static string operator +(Person p1, Person p2)
        {
            return p1.Name + p2.Name;
        }

        public static Person operator ++(Person p)
        {
            p.age++;
            return p;
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person("张三", 20);
            Person p2 = new Person("李四", 30);
            //string username = p1 + p2; //自定义对象隐式转换
            //Console.WriteLine(username);

            //Person p3 = "王五"; //强转,与视频中不同的时前面没有加括号
            //Person p3a = (Person)"赵六"; //视频中加了括号强转
            //Console.WriteLine(p3.Name + " " + p3.age.ToString());
            //Console.WriteLine(p3a.Name + " " + p3a.age.ToString());

            //string username = p1 + p2; //自定义对象 + 重载
            //Console.WriteLine(username);

            p1++;

            Console.WriteLine(p1.age.ToString());

            Console.ReadLine();
        }
    }
}

 运行结果(略)

附一个微软的例子

public readonly struct Fraction
{
    private readonly int num;
    private readonly int den;

    public Fraction(int numerator, int denominator)
    {
        if (denominator == 0)
        {
            throw new ArgumentException("Denominator cannot be zero.", nameof(denominator));
        }
        num = numerator;
        den = denominator;
    }

    public static Fraction operator +(Fraction a) => a;
    public static Fraction operator -(Fraction a) => new Fraction(-a.num, a.den);

    public static Fraction operator +(Fraction a, Fraction b)
        => new Fraction(a.num * b.den + b.num * a.den, a.den * b.den);

    public static Fraction operator -(Fraction a, Fraction b)
        => a + (-b);

    public static Fraction operator *(Fraction a, Fraction b)
        => new Fraction(a.num * b.num, a.den * b.den);

    public static Fraction operator /(Fraction a, Fraction b)
    {
        if (b.num == 0)
        {
            throw new DivideByZeroException();
        }
        return new Fraction(a.num * b.den, a.den * b.num);
    }

    public override string ToString() => $"{num} / {den}";
}

public static class OperatorOverloading
{
    public static void Main()
    {
        var a = new Fraction(5, 4);
        var b = new Fraction(1, 2);
        Console.WriteLine(-a);   // output: -5 / 4
        Console.WriteLine(a + b);  // output: 14 / 8
        Console.WriteLine(a - b);  // output: 6 / 8
        Console.WriteLine(a * b);  // output: 5 / 8
        Console.WriteLine(a / b);  // output: 10 / 4
    }
}

参考讲解实例,老师讲得非常好,希望大家多多关注ub主

c shape c# 自定义隐式转换与运算符重载_哔哩哔哩_bilibiliicon-default.png?t=N176https://www.bilibili.com/video/BV1rg411A7QU/?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=e821a225c7ba4a7b85e5aa6d013ac92e

特此记录

anlog

2023年2月11日

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/340123.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

电子科技大学操作系统期末复习笔记(一):操作系统概述

目录 前言 操作系统概述 操作系统的目标与功能 操作系统的定义 目标 功能 操作系统的历史 单用户系统 简单批处理系统 多道批处理系统 分时系统 个人电脑 → 分布式系统 → 互联网时代 → 移动计算时代 → ...... 实时系统 操作系统的基本特征 并发 共享 虚拟…

第一章 PDF语法

第一章 PDF语法PDF ObjectsNull ObjectsBoolean ObjectsNumeric ObjectsName ObjectsString ObjectsArray ObjectsDictionary ObjectsName treesNumber treesStream ObjectsDirect versus Indirect ObjectsFile StructureWhite-SpaceThe Four Sections of a PDFHeaderTrailerBo…

Sa-Token实现分布式登录鉴权(Redis集成 前后端分离)

文章目录1. Sa-Token 介绍2. 登录认证2.1 登录与注销2.2 会话查询2.3 Token 查询3. 权限认证3.1 获取当前账号权限码集合3.2 权限校验3.3 角色校验4. 前后台分离&#xff08;无Cookie模式&#xff09;5. Sa-Token 集成 Redis6. SpringBoot 集成 Sa-Token6.1 创建项目6.2 添加依…

Python 高级编程之网络编程 Socket(六)

文章目录一、概述二、Python socket 模块1&#xff09;Socket 类型1、创建 TCP Socket2、创建 UDP Socket2&#xff09;Socket 函数1、服务端socket函数2、客户端socket函数3、公共socket函数三、单工&#xff0c;半双工以及全双工通信方式的区别四、单工&#xff0c;半双工以及…

MWORKS--MoHub介绍

MWORKS--MoHub介绍1 介绍1.1 简介1.2 功能特征2 快速上手2.1 进入工作台2.2 新建仓库并进入建模空间2.3 建模进入建模工作空间加载模型库新建模型2.4 仿真2.5 后处理曲线、动画2.6 查看模型信息3 使用手册参考1 介绍 1.1 简介 MWORKS.MoHub 支持工业知识、经验、数据的模型化…

电子技术——BJT差分输入对

电子技术——BJT差分输入对 本节我们来讨论BJT差分输入对。 共模输入 下图是BJT差分输入对的基本原理图&#xff1a; 首先我们考虑两端输入共模信号 VCMV_{CM}VCM​ &#xff1a; 此时 vB1vB2VCMv_{B1} v_{B2} V_{CM}vB1​vB2​VCM​ 因为电路的对称结构&#xff0c;所以 i…

LeetCode 热题 C++ 114. 二叉树展开为链表

给你二叉树的根结点 root &#xff0c;请你将它展开为一个单链表&#xff1a; 展开后的单链表应该同样使用 TreeNode &#xff0c;其中 right 子指针指向链表中下一个结点&#xff0c;而左子指针始终为 null 。展开后的单链表应该与二叉树 先序遍历 顺序相同。 示例 1&#xf…

详细解读503服务不可用的错误以及如何解决503服务不可用

文章目录1. 问题引言2. 什么是503服务不可用错误3 尝试解决问题3.1 重新加载页面3.2 检查该站点是否为其他人关闭3.3 重新启动设备3.3 联系网站4. 其他解决问的方法1. 问题引言 你以前遇到过错误503吗&#xff1f; 例如&#xff0c;您可能会收到消息&#xff0c;如503服务不可…

ccc-Logistic Regression-李宏毅(5)

文章目录Step 1: Function SetStep 2: Goodness of a FunctionStep 3: Find the best functionWhy not Logistic Regression Square ErrorDiscriminative v.s. GenerativeMulti-class Classification(3 Class)Limitation of Logistic RegressionCascading logistic regression…

sklearn降维算法1 - 降维思想与PCA实现

目录1、概述1.1 维度概念2、PCA与SVD2.1 降维实现2.2 重要参数n_components2.2.1 案例&#xff1a;高维数据的可视化2.2.2 最大似然估计自选超参数2.2.3 按信息量占比选超参数1、概述 1.1 维度概念 shape返回的结果&#xff0c;几维几个方括号嵌套 特征矩阵特指二维的 一般来…

pwn手记录题2

fastbin_reverse_into_tcache(2.34) 本题所使用的libc版本为2.34&#xff1b;&#xff08;最新版 libc2.34版本已经没有了所谓的hook函数&#xff0c;甚至exit_hook(实际为某个函数指针)也已经不能够使用&#xff1b;能够利用的手法已经很少了&#xff1b; 高版本glibc堆的几…

进程间通信(上)

进程间通信&#xff08;上&#xff09;背景进程间通信目的进程间通信发展进程间通信分类管道什么是管道匿名管道实例代码简单的匿名管道实现一个父进程控制单个子进程完成指定任务父进程控制一批子进程完成任务&#xff08;进程池&#xff09;用fork来共享管道站在文件描述符角…

C++:类和对象(中)

文章目录1 类的6个默认成员函数2 构造函数2.1 概念2.2 特性3 析构函数3.1 概念3.2 特性4 拷贝构造函数4.1 概念4.2 特性5 赋值运算符重载5.1 运算符重载5.2 赋值运算符重载5.3 前置重载和后置重载6 日期类的实现7 const成员8 取地址及const取地址操作符重载1 类的6个默认成员函…

【C++初阶】十三、模板进阶(总)|非类型模板参数|模板的特化|模板分离编译|模板总结(优缺点)

目录 一、非类型模板参数 二、模板的特化 2.1 模板特化概念 2.2 函数模板特化 2.3 类模板特化 2.3.1 全特化 2.3.2 偏特化 三、模板分离编译 四、模板总结&#xff08;优缺点&#xff09; 前言&#xff1a;之前模板初阶并没有把 C模板讲完&#xff0c;因为当时没有接触…

Java——聊聊JUC中的原子变量类

文章目录&#xff1a; 1.什么是原子变量类&#xff1f; 2.AtomicInteger&#xff08;基本类型原子变量类&#xff09; 3.AtomicIntegerArray&#xff08;数组类型原子变量类&#xff09; 4.AtomicMarkableReference&#xff08;引用类型原子变量类&#xff09; 5.AtomicInteger…

二叉树OJ题(上)

✅每日一练&#xff1a;100. 相同的树 - 力扣&#xff08;LeetCode&#xff09; 题目的意思是俩棵树的结构不仅要相同&#xff0c;而且每个节点的值还要相同&#xff0c;如果满足上面2个条件&#xff0c;则成立&#xff01; 解题思路&#xff1a; 从三个方面去考虑&#xff1…

分布式之分布式事务V2

写在前面 本文一起来看下分布式环境下的事务问题&#xff0c;即我们经常听到的分布式事务问题。想要解决分布式事务问题&#xff0c;需要使用到分布式事务相关的协议&#xff0c;主要有2PC即两阶段提交协议&#xff0c;TCC&#xff08;try-confirm-cancel&#xff09;&#xf…

FPGA产业发展现状及人才培养研究报告

文章目录一、FPGA赋能智能时代二、FPGA市场现状及挑战2.1 FPGA市场发展现状2.2 FPGA主要应用场景2.3 人才问题成为FPGA发展的桎梏三、FPGA人才需求与人才培养3.1 FPGA人才需求特征3.2 FPGA人才培养现状3.2.1 培养主体3.2.2 培养机制3.2.3 培养人才的目的和宗旨3.2.4 FPGA人才培…

【C++】六个默认成员函数——取地址重载,const成员函数

&#x1f345; 初始化和清理 拷贝复制 目录 ☃️1.取地址重载 ☃️2.const取地址操作符重载 这两个运算符一般不需要重载&#xff0c;使用编译器生成的默认取地址的重载即可&#xff0c;只有特殊情况&#xff0c;才需要重载&#xff0c;比如想让别人获取到指定的内容&#xf…

计算机网络3:HTTP1.0和HTTP1.1的区别

目录1. HTTP是什么2.HTTP1.0和HTTP1.1的区别3.名词解释&#xff08;1&#xff09;If-Modified-Since&#xff08;IMS&#xff09;、Expires&#xff08;2&#xff09;If-None-Match&#xff0c;Etag&#xff08;3&#xff09;If-Unmodified-Since1. HTTP是什么 超文本传输协议…