3

私はドキュメントジェネレーターに取り組んでいます。MSDN のドキュメントには、適用時に属性に渡されるパラメーターが示されています。など[ComVisibleAttribute(true)]。リフレクション、pdb ファイルなどを介して、C# コードで呼び出されたこれらのパラメーター値やコンストラクターを取得するにはどうすればよいですか?

明確にするために>誰かが次のように属性を持つメソッドを文書化した場合:

/// <summary> foo does bar </summary>
[SomeCustomAttribute("a supplied value")]
void Foo() {
  DoBar();
}

次のように、ドキュメントにメソッドのシグネチャを表示できるようにしたいと考えています。

Signature:

[SomeCustomAttribute("a supplied value")]
void Foo();
4

2 に答える 2

6

カスタム属性とコンストラクター引数を取得するメンバーがある場合は、次のリフレクションコードを使用できます。

MemberInfo member;      // <-- Get a member

var customAttributes = member.GetCustomAttributesData();
foreach (var data in customAttributes)
{
    // The type of the attribute,
    // e.g. "SomeCustomAttribute"
    Console.WriteLine(data.AttributeType);

    foreach (var arg in data.ConstructorArguments)
    {
        // The type and value of the constructor arguments,
        // e.g. "System.String a supplied value"
        Console.WriteLine(arg.ArgumentType + " " + arg.Value);
    }
}

メンバーを取得するには、タイプの取得から始めます。タイプを取得するには2つの方法があります。

  1. インスタンスがある場合objは、を呼び出しますType type = obj.GetType();
  2. タイプ名がある場合はMyType、を実行しますType type = typeof(MyType);

次に、たとえば、特定のメソッドを見つけることができます。詳細については、リフレクションのドキュメントを参照してください。

MemberInfo member = typeof(MyType).GetMethod("Foo");
于 2013-02-21T23:14:45.767 に答える
3

の場合、ComVisibileAttributeコンストラクターに渡されたパラメーターがValueプロパティになります。

[ComVisibleAttribute(true)]
public class MyClass { ... }

...

Type classType = typeof(MyClass);
object[] attrs = classType.GetCustomAttributes(true);
foreach (object attr in attrs)
{
    ComVisibleAttribute comVisible = attr as ComVisibleAttribute;
    if (comVisible != null)
    {
        return comVisible.Value // returns true
    }
}

他の属性も同様のデザインパターンに従います。


編集

非常によく似た方法を説明しているMono.Cecilに関するこの記事を見つけました。これはあなたが必要なことをするべきだと思われます。

foreach (CustomAttribute eca in classType.CustomAttributes)
{
    Console.WriteLine("[{0}({1})]", eca, eca.ConstructorParameters.Join(", "));
}
于 2013-02-21T23:03:12.830 に答える