I've written (using a sneak peek on the net) my generic method to get attributes on classnames. Here is the code.
The attribute:
[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class FileType : Attribute
{
public String TypeName { get; set; }
}
The implementation
[FileType (TypeName ="wordFile")]
public class BudFile
{ ... }
My Generic Method
public T GetAttributeOfObject<T>(Type objectTypeToCheck)
{
object myAttribute = (T)Attribute.GetCustomAttribute(objectTypeToCheck, typeof(T));
}
The Usage:
BudFile A;
FileType myFileType = GetAttributeOfObject<FileType>(typeof(A));
The Problem:
I'm getting the error Cannot convert type System.Attribute to T
on the following line:
object myAttribute = (T)Attribute.GetCustomAttribute(objectTypeToCheck, typeof(T));
Which makes sense since Attribute.GetCustomAttribute
returns an object of System.Attribute
. How can I Safely cast the retrieved System.Attribute
to my attribute?
Aucun commentaire:
Enregistrer un commentaire