gpt4 book ai didi

C# 访问者模式表达式构建结果度量单位

转载 作者:太空宇宙 更新时间:2023-11-03 14:16:10 24 4
gpt4 key购买 nike

我正在着手进行一个涉及一些计算的项目,并已开始使用基于 Cureos 框架的相当简单的 UOM(计量单位)改编。到目前为止一切顺利,我已经展示了一些基本单位。

我想做的一件事是在基础单位的基础上构建以得出计算值。例如,如果我们有长度(或距离)和时间,我们可以得到速度(距离/时间)或加速度(距离/平方(时间))。

我的单位很灵活;我可以将它们显示为英语、SI 或任何系统碰巧以我需要的任何数量显示,无论是英尺、英寸、米、厘米等。或者在时间的情况下,毫秒、秒、分钟等。

我想做的是报告计算时的实际单位。因此,如果单位是米和秒,我想为速度报告“m/s”或为加速度报告“m/s^2”。或者,如果单位是英尺和毫秒,则分别报告“ft/ms”或“ft/ms^2”。

所以...以这个故事为背景,我很乐意将这些更复杂的单元(如果您愿意,也许它是一个单元,也许不是...那是待定的)表达为 Linq 表达式树,借此我可以合理地访问整个表达式树的节点以获取其单元,并“编译”单元名称以及实际的数字结果。

如果涉及的对象是 Measures(对于可量化的值)、Units(对于单位)和 Quantities(对于单位的种类),在我看来这应该是完全可行的。

想法?

最佳答案

我不确定您在这里要求什么,但是当遇到在我的程序中维护不同变量的单位并找到结果值的正确单位的问题时,这就是我想出的解决方案。

using System;

namespace ConsoleApplication1
{
public interface Mass
{
}

public class Kg: Mass
{
}

public interface Length
{
}

public interface M : Length
{
}

public interface M<in T>: M where T: M, Length
{
}

public interface Time
{
}

public interface S : Time
{
}

public interface S<in T> : S where T : S, Time
{
}

public interface IUnit<in M, in L, in T>
where M: Mass
where L: Length
where T: Time
{
}

public sealed class Unit<M, L, T>: IUnit<M, L, T>
where M : Mass
where L : Length
where T : Time
{
public static Unit<M, L, T> operator +(Unit<M, L, T> a, Unit<M, L, T> b)
{
throw new NotImplementedException();
}
}

public interface Nil: Mass, Length, Time
{
}

class Program
{
static void Main(string[] args)
{
Unit<Nil, M, S<S>> value1 = null;
Unit<Nil, M, S<S>> value2 = null;

var result = value1 + value2;
}
}
}

这将允许您在返回其他单位的单位上定义运算符(简单的 MLT 数学)。请注意,S 实际上是 S^2,是我想出的实现此功能的最易读的方式。

希望这对您有所帮助!

关于C# 访问者模式表达式构建结果度量单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6541076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com