[英]Casting: System.Attribute retrieved from Objecttypes
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: 我在以下行收到错误
Cannot convert type System.Attribute to T
”:
object myAttribute = (T)Attribute.GetCustomAttribute(objectTypeToCheck, typeof(T));
Which makes sense since Attribute.GetCustomAttribute
returns an object of System.Attribute
. 这很有意义,因为
Attribute.GetCustomAttribute
返回System.Attribute
的对象。 How can I Safely cast the retrieved System.Attribute
to my attribute? 如何安全地将检索到的
System.Attribute
为我的属性?
You simply need a constraint for T
as Attribute
. 您只需要将
T
作为Attribute
的约束即可。 You get the compiler error because T
could be anything which can't be casted to an Attribute
type. 您会收到编译器错误,因为
T
可能是任何不能转换为Attribute
类型的值。
public T GetAttributeOfObject<T>(Type objectTypeToCheck) where T: Attribute
{
return (T)Attribute.GetCustomAttribute(objectTypeToCheck, typeof(T));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.