转换:System.Attribute 从 Objecttypes 检索

Casting: System.Attribute retrieved from Objecttypes

我已经编写了(在网上先睹为快)获取类名属性的通用方法。这是代码。

属性:

[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class FileType : Attribute
{
    public String TypeName { get; set; }
}

执行

[FileType (TypeName ="wordFile")]
public class BudFile
{ ... }

我的通用方法

    public T GetAttributeOfObject<T>(Type objectTypeToCheck)
    {
        object myAttribute = (T)Attribute.GetCustomAttribute(objectTypeToCheck, typeof(T));
    }

用法:

BudFile A;
FileType myFileType = GetAttributeOfObject<FileType>(typeof(A));

问题:

我在以下行收到错误 Cannot convert type System.Attribute to T

        object myAttribute = (T)Attribute.GetCustomAttribute(objectTypeToCheck, typeof(T));

这是有道理的,因为 Attribute.GetCustomAttribute returns 是 System.Attribute 的一个对象。我怎样才能安全地 将检索到的 System.Attribute 转换为我的属性?

您只需要 T 作为 Attribute 的约束。您会收到编译器错误,因为 T 可能是无法转换为 Attribute 类型的任何内容。

public T GetAttributeOfObject<T>(Type objectTypeToCheck) where T: Attribute
{
    return (T)Attribute.GetCustomAttribute(objectTypeToCheck, typeof(T));
}