123

クラスの属性を読み取り、実行時にその値を返す汎用メソッドを作成しようとしています。どうすればいいですか?

注: DomainName 属性は、クラス DomainNameAttribute のものです。

[DomainName("MyTable")]
Public class MyClass : DomainBase
{}

私が生成しようとしているもの:

//This should return "MyTable"
String DomainNameValue = GetDomainName<MyClass>();
4

9 に答える 9

266
public string GetDomainName<T>()
{
    var dnAttribute = typeof(T).GetCustomAttributes(
        typeof(DomainNameAttribute), true
    ).FirstOrDefault() as DomainNameAttribute;
    if (dnAttribute != null)
    {
        return dnAttribute.Name;
    }
    return null;
}

アップデート:

このメソッドは、任意の属性で動作するようにさらに一般化できます。

public static class AttributeExtensions
{
    public static TValue GetAttributeValue<TAttribute, TValue>(
        this Type type, 
        Func<TAttribute, TValue> valueSelector) 
        where TAttribute : Attribute
    {
        var att = type.GetCustomAttributes(
            typeof(TAttribute), true
        ).FirstOrDefault() as TAttribute;
        if (att != null)
        {
            return valueSelector(att);
        }
        return default(TValue);
    }
}

次のように使用します。

string name = typeof(MyClass)
    .GetAttributeValue((DomainNameAttribute dna) => dna.Name);
于 2010-04-16T21:30:25.713 に答える
16
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);

for (int i = 0; i < attributes.Length; i++)
{
    if (attributes[i] is DomainNameAttribute)
    {
        System.Console.WriteLine(((DomainNameAttribute) attributes[i]).Name);
    }   
}
于 2010-04-16T21:31:12.570 に答える
0
' Simplified Generic version. 
Shared Function GetAttribute(Of TAttribute)(info As MemberInfo) As TAttribute
    Return info.GetCustomAttributes(GetType(TAttribute), _
                                    False).FirstOrDefault()
End Function

' Example usage over PropertyInfo
Dim fieldAttr = GetAttribute(Of DataObjectFieldAttribute)(pInfo)
If fieldAttr IsNot Nothing AndAlso fieldAttr.PrimaryKey Then
    keys.Add(pInfo.Name)
End If

おそらく、ジェネリック関数の本体をインラインで使用するのと同じくらい簡単です。関数を型 MyClass に対してジェネリックにすることは、私には意味がありません。

string DomainName = GetAttribute<DomainNameAttribute>(typeof(MyClass)).Name
// null reference exception if MyClass doesn't have the attribute.
于 2015-04-14T22:21:44.653 に答える
-1

多くのコードを書くのではなく、次のようにしてください。

{         
   dynamic tableNameAttribute = typeof(T).CustomAttributes.FirstOrDefault().ToString();
   dynamic tableName = tableNameAttribute.Substring(tableNameAttribute.LastIndexOf('.'), tableNameAttribute.LastIndexOf('\\'));    
}
于 2019-11-08T22:05:31.890 に答える