KO CSharp Keyword unmanaged generic type constraint - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki
ะฃะบัะฐัะฝััะบะฐ ยท ะ ัััะบะธะน ยท English ยท Deutsch ยท Franรงais ยท Italiano ยท Espaรฑol ยท ็น้ซไธญๆ ยท ๆฅๆฌ่ช ยท ํ๊ตญ์ด
ํธ๋๋ถ C# ยท ์ค์ฉ ๊ฐ์ด๋
where T : unmanaged ์ ์ฝ ์กฐ๊ฑด์ ๊ตฌ์ฑ์์ ๊ด๋ฆฌ๋๋ ์ฐธ์กฐ๊ฐ ์๋ ๊ฐ ์ ํ๋ง ํ์ฉํฉ๋๋ค. ํ์ฉ๋ ์์ ํ์ง ์์ ์ปจํ ์คํธ์์ sizeof(T) ๋ฐ T*๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค. ์ด๋ ํจ์ ํธ์ถ ๊ท์น์ด ์๋ ์ ํ ์ ์ฝ ์กฐ๊ฑด์ ๋๋ค. ๋ณ๋์ ๊ตฌ์กฐ์ฒด๋ 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 ํ์ต.