ZH TW CSharp Keyword unmanaged generic type constraint - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
where T : 非託管約束僅允許其組合中沒有託管引用的值類型。它允許您在允許的不安全上下文中使用 sizeof(T) 和 T*。這是類型約束,而不是函數呼叫約定。它不與單獨的 struct 或 new() 組合。
請將此範例另存為 Example.cs,並與本頁其他範例分開執行。
Example.cs:
// PROJECT-EXAMPLE
int Size<T>() where T : unmanaged
{
unsafe { return sizeof(T); }
}
System.Console.WriteLine(Size<int>());結果:
4
static int ByteSize<T>() where T : unmanaged;
static void Swap<T>(T* left, T* right) where T : unmanaged;文件Example.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
</Project>文件Program.cs:
using System;
public struct GridPoint { public int X; public int Y; }
internal static unsafe class Program
{
public static void Main()
{
Console.WriteLine(ByteSize<int>());
Console.WriteLine(ByteSize<GridPoint>());
}
private static int ByteSize<T>() where T : unmanaged => sizeof(T);
}結果:
4
8
文件Example.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
</Project>文件Program.cs:
using System;
internal static unsafe class Program
{
public static void Main()
{
int left = 10;
int right = 25;
Swap(&left, &right);
Console.WriteLine($"{left},{right}");
}
private static void Swap<T>(T* left, T* right) where T : unmanaged
{
T temporary = *left;
*left = *right;
*right = temporary;
}
}結果:
25,10
官方來源:Microsoft學習。