C#-自定义类型转换与重写运算符,typeof()的使用

C#自定义类型转换与重写运算符,typeof()的使用

原创彩色墨水 发布于2019-08-30 11:54:48 阅读数 18  收藏

每天学习一点点,然后做练习巩固下

注意不管是重写运算符还是 自定义类型转换,都必须写在 被操作的类里面,基于这条规定,想把重写运算符写成工具类,是不能够的.
工具类是被抽象出来的类,和想要操作的对象或类不相同. 重写运算符方法或自定义类型转换方法或报错.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestCustomConv : MonoBehaviour{
    void Start()
    {
        float temp1 = new ABC();//可以隐式转换
        int temp2 = (int)new ABC();//可以显式转换
        //float temp3 = new DDD();//不具备转换关系
        DEF temp4 = (DEF)new ABC();//类之间的显式转换
        Debug.Log("temp1:" + temp1);//打印ABC隐士转换成float后的值
        Debug.Log("temp2:" + temp2);//打印ABC显示转换成int后的值
        Debug.Log("temp4:" + temp4);//打印ABC显示转化成DEF后的内容 ,为类名
        Debug.Log("temp4.def:" + temp4.def);//打印对应的值
        ABC temp5 = (ABC)new DEF();//DEF转ABC
        float temp6 = temp5 + (DEF)temp5;//重载运算符会优先于隐士转换
        Debug.Log("temp5:" + temp5);//temp5为ABC类型,具备隐士转换为float的定义,可直接打印值
        Debug.Log("temp5.abc:" + temp5.abc);//打印属性abc
        Debug.Log("temp6:" + temp6);//打印 temp5(ABC) 与(DEF)temp5 +后的结果;如果没有重写运算符+ 对 ABC 和 DEF操作,那么 temp5(ABC) 与(DEF)temp5 会隐式转换为float 相加, 如果有重载有重写运算符+ 会执行 重写运算符方法中的内容.
    }
}

public class ABC{
    public float abc;
    public ABC() {
        abc = 99;
    }

    public static implicit operator float(ABC aBC)//隐式转换,相当于在类内部将自身的特性修改了或者是改造了,让我这个类具备转换成其它类型的能力,当然转换成什么,是在内部定义好的.可以隐式转换也可以显式转换.
    {
        return aBC.abc * 10;
    }

    public static explicit operator int(ABC aBC)//显式转换
    {
        return (int)aBC.abc - 10;
    }

    public static explicit operator DEF(ABC aBC)
    {
        return new DEF(aBC.abc);
    }
}
public class DDD
{
    float ddd;
}

public class DEF
{
    public int def;
    public DEF(float temp)
    {
        def = (int)temp;
    }

    public DEF() { }

    public static explicit operator ABC(DEF dEF)
    {
        return new ABC();
    }
    public static explicit operator int(DEF dEF)
    {
        return (int)dEF.def;
    }
    public static implicit operator float(DEF dEF)
    {
        return dEF.def;
    }

    public static float operator -(ABC aBC, DEF dEF)
    {
        return aBC * 100 + dEF * 100;
    }
}


在这里插入图片描述

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

public class TestTypeOf : MonoBehaviour
{
    void Start()
    {
        Type type = typeof(BisonBasicData);
        FieldInfo[] fieldInfos = type.GetFields();
        MethodInfo[] methodInfos = type.GetMethods();
        for (int i = 0; i < fieldInfos.Length; i++)
        {
            Debug.Log(fieldInfos[i].Name);
        }
        Debug.Log("-----------------------------------------------");
        foreach (var item in methodInfos)
        {
            Debug.Log(item.Name);
        }
    }


}

在这里插入图片描述

原文地址:https://www.cnblogs.com/grj001/p/12223139.html