首页 \ 问答 \ Unsafe.AsPointer (ref T值)如何工作?(How Unsafe.AsPointer(ref T value) works?)

Unsafe.AsPointer (ref T值)如何工作?(How Unsafe.AsPointer(ref T value) works?)

在C#中,您不能创建指向托管类型的指针,但使用此API,您可以使用Unsafe.AsPointer<T>

https://www.nuget.org/packages/System.Runtime.CompilerServices.Unsafe/

我看到使用ILSpy的源代码,我看到了这个:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.Versioning.NonVersionable]
public unsafe static void* AsPointer<T>(ref T value)
{
    return &value;
}

另外在其他类似的API中:

//Unity.Collections.LowLevel.Unsafe.UnsafeUtility
public unsafe static T ReadArrayElement<T>(void* source, int index)
{
    return *(T*)((byte*)source + index * sizeof(T));
}

这是如何工作的以及如何复制这种行为?


In C# you're not suppose to be able to create pointer to managed types but with this API you are able to, using Unsafe.AsPointer<T>.

https://www.nuget.org/packages/System.Runtime.CompilerServices.Unsafe/

I see the source code using ILSpy and I saw this:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.Versioning.NonVersionable]
public unsafe static void* AsPointer<T>(ref T value)
{
    return &value;
}

Also in other similar API:

//Unity.Collections.LowLevel.Unsafe.UnsafeUtility
public unsafe static T ReadArrayElement<T>(void* source, int index)
{
    return *(T*)((byte*)source + index * sizeof(T));
}

How this works and how is possible to replicate that behaviour?


原文:https://stackoverflow.com/questions/51599375
更新时间:2023-11-21 18:11

最满意答案

您正在寻找一种通用方法:

private static void SetEntityPropertiesRequired<TEntity>(DbModelBuilder modelBuilder)
{
    //set all decimal properties in Projection Entity to be Required
    var decimalproperties = typeof (TEntity).GetProperties()
    ...

You're looking for a generic method:

private static void SetEntityPropertiesRequired<TEntity>(DbModelBuilder modelBuilder)
{
    //set all decimal properties in Projection Entity to be Required
    var decimalproperties = typeof (TEntity).GetProperties()
    ...

相关问答

更多