受到F#中的度量单位的启发,尽管断言(这里)你无法用C#做到这一点,但我还有一个想法,那就是我一直在玩的.
namespace UnitsOfMeasure
{
public interface IUnit { }
public static class Length
{
public interface ILength : IUnit { }
public class m : ILength { }
public class mm : ILength { }
public class ft : ILength { }
}
public class Mass
{
public interface IMass : IUnit { }
public class kg : IMass { }
public class g : IMass { }
public class lb : IMass { }
} …Run Code Online (Sandbox Code Playgroud) 我试图通过将double包装到struct中来获得我称之为测量单位系统的东西.我有C#结构,如Meter,Second,Degree等.我最初的想法是,在编译器内联所有内容后,我将获得与使用double时相同的性能.
我的显式和隐式运算符简单明了,编译器实际上内联它们,但是Meter和Second的代码比使用double的相同代码慢10倍.
我的问题是:为什么C#编译器不能使用Second作为使用double的代码的最佳代码,如果它无论如何都要内联?
第二个定义如下:
struct Second
{
double _value; // no more fields.
public static Second operator + (Second left, Second right)
{
return left._value + right._value;
}
public static implicit Second operator (double value)
{
// This seems to be faster than having constructor :)
return new Second { _value = value };
}
// plenty of similar operators
}
Run Code Online (Sandbox Code Playgroud)
更新:
我没有问结构是否适合这里.确实如此.
我没有询问代码是否会被内联.JIT确实内联它.
我检查了运行时发出的汇编操作.对于像这样的代码,它们是不同的:
var x = new double();
for (var i = 0; i < 1000000; i++)
{ …Run Code Online (Sandbox Code Playgroud) 我想把华氏温度转换成摄氏温度.
做以下我总是得到零:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Celcius_Farenheit_Converter
{
class Program
{
static double Celcius(double f)
{
double c = 5/9*(f - 32);
return c;
}
static void Main(string[] args)
{
string text = "enter a farenheit tempature";
double c = Celcius(GetTempature(text));
Console.WriteLine("the tempature in Celicus is {0}", c);
Console.ReadKey(true);
}
static double GetTempature(string text)
{
Console.WriteLine(text);
bool IsItTemp = false;
double x = 0;
do
{
IsItTemp = double.TryParse(Console.ReadLine(), out x);
} while …Run Code Online (Sandbox Code Playgroud)