当前位置: 首页 > news >正文

接口实现C#泛型四则运算

一般我们会对泛型字段做封装,使其支持OnChange、IsDirty等字段功能扩展,例如:

IObservable<float> hitPoint;

 

而有些字段则有挂载修改器的需求,修改器若使用lambda则对序列化不友好,因此考虑自行封装四则运算供修改器

给原始数值进行修改,但C#早期没有四则运算的接口。网上的dynamic动态类型做法对多平台并不友好。

 

不转弱类型的情况下,考虑通过接口解决,代码如下:

public interface IArithmeticOperator<T>
{public T Add(T x, T y);public T Sub(T x, T y);public T Mul(T x, T y);public T Div(T x, T y);
}public static class ArithmeticOperator<T>
{public static IArithmeticOperator<T> Instance;static ArithmeticOperator(){var type = typeof(T);if (type == typeof(int))Instance = (IArithmeticOperator<T>)(object)new IntAritOp();else if (type == typeof(float))Instance = (IArithmeticOperator<T>)(object)new FloatAritOp();}
}public class IntAritOp : IArithmeticOperator<int>
{public int Add(int x, int y) => x + y;public int Div(int x, int y) => x / y;public int Mul(int x, int y) => x * y;public int Sub(int x, int y) => x - y;
}public class FloatAritOp : IArithmeticOperator<float>
{public float Add(float x, float y) => x + y;public float Div(float x, float y) => x / y;public float Mul(float x, float y) => x * y;public float Sub(float x, float y) => x - y;
}public class AttributeModifier<T>
{private T _delta;public AttributeModifier(T delta) { this._delta = delta; }public T Add(T current) => ArithmeticOperator<T>.Instance.Add(current, _delta);public T Sub(T current) => ArithmeticOperator<T>.Instance.Sub(current, _delta);public T Mul(T current) => ArithmeticOperator<T>.Instance.Mul(current, _delta);public T Div(T current) => ArithmeticOperator<T>.Instance.Div(current, _delta);
}public class Test01 : MonoBehaviour
{void Start(){var op01 = new AttributeModifier<int>(10);var op02 = new AttributeModifier<int>(2);int hitPoint = 0;hitPoint = op01.Add(hitPoint);hitPoint = op02.Mul(hitPoint);Debug.Log(hitPoint);//20var op03 = new AttributeModifier<float>(4.5f);var op04 = new AttributeModifier<float>(2.2f);float stamina = 0f;stamina = op03.Add(stamina);stamina = op04.Mul(stamina);Debug.Log(stamina);//9.900001
    }
}

 

http://www.gsyq.cn/news/39076.html

相关文章:

  • [Flink/Hologres/汽车] 骋在数据洪流上:Flink+Hologres驱动零跑科技实时计算的应用与实践 [转]
  • 读《Python神经网络编程(异步图书) 塔里克拉希德》有感
  • 【CI130x 离在线】Python使用import opuslib 报错解决方案
  • 蒟蒻的S游记碎碎念
  • 【python刷题记录】移动零-双指针-简单
  • 002 vue3-admin项目的目录及文件说明之public目录
  • Day11CSS特性
  • Maya 2025软件超详细下载安装教程(附安装包和激活步骤)
  • 一款基于 .NET WinForm 开源、轻量且功能强大的节点编辑器,采用纯 GDI+ 绘制无任何依赖库仅仅100+Kb!
  • docker compose.yaml配置
  • Multisim保姆级图文下载安装教程包含下载、安装、汉化、激活
  • JMeter生包
  • 20251103 - 折半搜索 总结
  • NPI
  • Edge插件导入到chrome浏览器
  • CF Pinely Round 5(#2161) 总结
  • 收藏!强化学习从入门到封神:5 本经典教材 + 8 大实战项目 + 7个免费视频,一站式搞定 - AI
  • 拾壹月Ⅲ
  • 20251103周一日记
  • Window 安装多个 MySQL 实例 - Higurashi
  • 普赛斯
  • 25.11.03
  • win10安装neo4j-community-3.5.7-windows
  • 阅读笔记0
  • 个体户办理食品经营须知
  • 2025.11.3——1绿1蓝
  • 2025.11.3 - A
  • 【每日一面】实现一个深拷贝函数
  • MySQL排序算法
  • 20232314 2024-2025-1 《网络与系统攻防技术》实验四实验报告