JA CSharp Keyword where generic type constraint - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: where — タイプパラメータ制限

ディレクトリ C# · 実践的な指導

型パラメーターの要件を指定します: 基本クラス、インターフェイス、クラス/構造体、new()、notnull、アンマネージ、およびその他の許可される組み合わせ。

簡単な例 (Example.cs)

この例を Example.cs として別に保存し、このページの他の例とは独立して実行してください。

Example.cs:

// PROJECT-EXAMPLE
T Create<T>() where T : new() => new T();
System.Console.WriteLine(Create<Item>().Name);
class Item { public string Name => "Ore"; }

結果:

Ore

構文

where T : constraint1, constraint2

例 1: 基本形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Counter counter = Factory.Create<Counter>();
        Console.WriteLine(counter.Value);
    }
}
public class Counter { public int Value => 7; }
public static class Factory { public static T Create<T>() where T : class, new() => new T(); }

例 2: 別の実用的な形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Values.Sum<Number>());
    }
}
public interface IValue { int Value { get; } }
public readonly struct Number : IValue { public int Value => 5; }
public static class Values { public static int Sum<T>() where T : struct, IValue { T value = new(); return value.Value; } }

公式ソース: Microsoft Learn。

⚠️ **GitHub.com Fallback** ⚠️