为了减少我正在开发的库中的维护,我试图将类似的功能委托给单个函数.例如,假设一个具有双组件向量,其中Add函数接受by-ref args,而其他函数接受by-value args.我们的想法是简单地在by-value函数中调用by-ref函数,使其只需要维护by-ref函数.
即
struct Vector2
{
public float X;
public float Y;
public Vector2(float x, float y)
{
this.X = x;
this.Y = y;
}
public static void Add(ref Vector2 a, ref Vector2 b, out Vector2 result)
{
result.X = a.X + b.X;
result.Y = a.Y + b.Y;
}
public static Vector2 Add1(Vector2 a, Vector2 b)
{
Add(ref a, ref b, out a);
return a;
}
public static Vector2 Add2(Vector2 a, Vector2 b)
{
a.X += b.X;
a.Y += …Run Code Online (Sandbox Code Playgroud) 更新了适用于我的解决方案.请参阅此问题的底部.
上下文:
我需要一种方法来评估泛型类型的大小,以便计算适合某个字节大小的数组长度.基本上,
sizeof类似于C/C++提供的.
C#sizeof和Marshal.SizeOf不适合这个,因为它们有很多限制.
考虑到这一点,我在IL中编写了一个程序集,它通过sizeof操作码启用了我正在寻找的功能.我知道它基本上IntPtr.Size用引用类型来评估.
我为.NET Standard&Core复制了这个,引用了我认为正确的mscorlib等价物.注意IL编译得很好,这个问题是另一个问题.
代码:
每个目标框架的标头:
.NET:(Windows\Microsoft.NET\Framework\v4.0.30319\ilasm.exe)
.assembly extern mscorlib {}
Run Code Online (Sandbox Code Playgroud)
.NET标准:(从nuget中提取的ilasm )
.assembly extern netstandard
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89)
.ver 0:0:0:0
}
.assembly extern System.Runtime
{
.ver 0:0:0:0
}
Run Code Online (Sandbox Code Playgroud)
.NET Core :(与标准相同,尽管我已经测试过两者)
.assembly extern System.Runtime
{
.ver 0:0:0:0
}
Run Code Online (Sandbox Code Playgroud)
资源:
.assembly Company.IL
{
.ver 0:0:1:0
}
.module Company.IL.dll
// CORE is a define for mscorlib, netstandard, and …Run Code Online (Sandbox Code Playgroud) 在业余时间,我一直在研究一个实用程序库,除其他外,它支持有符号/无符号的128位整数.在某些情况下,此库使用cpu-dispatching来使用simd指令,但需要可移植的后备,因此它将在其他任何地方运行.最近我实现了128位移位的便携式回退.它运行正常并且运行速度相当快,但它没有我想要的那么快,尤其是在32位架构上.
这是一个带有所有相关类型和功能的剥离版本(包括完整性的64位版本):
typedef uint32_t UInt32;
typedef int32_t Int32;
typedef uint64_t UInt64;
typedef int64_t Int64;
// Returns 0xFFFFFFFF if value != 0, otherwise returns 0.
UInt32 AllOrNothingMask32(Int32 value)
{
return UInt32(-Int32(value != 0));
}
struct alignas(16) UInt128
{
// Ensure the layout matches the architecture.
// LE = little endian
// BE = big endian
#if CPU_TYPE == CPU_LE32
UInt32 mLow;
UInt32 mLowMid;
UInt32 mHighMid;
UInt32 mHigh;
#elif CPU_TYPE == CPU_BE32
UInt32 mHigh;
UInt32 mHighMid;
UInt32 mLowMid;
UInt32 mLow;
#elif CPU_TYPE …Run Code Online (Sandbox Code Playgroud)