なんかいろいろと書いてくブログ

関東のどこかで働く、一般人

【C# 11 Preview】Generic Attribute

前回の記事の続き C# 11 Previewを触ってみようというはなし 今回はVisual Studio 2022 17.1 からユーザ定義クラスGeneric Classで定義できるようになるらしい

注意

この記事はC# 11 Previewに関する記事になります

C# 11の仕様については今後変更される可能性があります 

Generic Attributes

docs.microsoft.com

以前までは、カスタム属性に対してジェネリックな Attributeを継承したクラスのコンストラクターを作成する必要がありました

public class CustomAttribute : Attribute
{
    public CustomAttribute(Type t) => param = t;

    public Type param { get; }
}

// typeofで型を渡す
[TypeAttribute(typeof(string))]
public string Method() => default;

C# 11からはGeneric Classで定義できるようになり、
書き方が簡素化されるよう

public class CustomAttribute<T> : Attribute { }


[CustomAttribute<string>()]
public string Method() => default;

ただし、Genericになっても、typeof 演算子で使用できない型は使えないよう