C#のAttributes.Add()の使い方

C#では、Attributes.Add() メソッドはカスタム属性を型、メンバー、またはアセンブリに追加するために使用されます。使用方法は次のとおりです。

  1. System.Attribute クラスを継承するカスタム属性クラスを作成します。たとえば、
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAttribute : Attribute
{
// 自定义属性的成员和方法
}
  1. 型、メンバーまたはアセンブリにカスタム属性を追加します。 例:
[CustomAttribute]
public class MyClass
{
[CustomAttribute]
public void MyMethod()
{
}
}
  1. カスタムプロパティを追加する必要がある場所に、Attributes.Add()メソッドを使用します。例:
using System.Reflection;
public class Program
{
public static void Main()
{
Type type = typeof(MyClass);
MethodInfo methodInfo = type.GetMethod("MyMethod");
CustomAttribute customAttribute = new CustomAttribute();
methodInfo.GetCustomAttributes().Add(customAttribute);
}
}

上のサンプルでは、MyClassのTypeオブジェクトをtypeof()メソッドで取得し、さらにGetMethod()メソッドでMyMethodのMethodInfoオブジェクトを取得しました。次に、CustomAttributeオブジェクトを作成し、Attributes.Add()メソッドでMyMethodメソッドに追加しました。

なお、Attributes.Add() メソッドは読み取り専用のコレクションの AttributeCollection 型のインスタンスを返却するため、直接的な変更はできません。追加したカスタム属性の変更や削除にはリフレクション機能を用いる必要があります。

bannerAds