简体   繁体   English

转换:从对象类型检索的System.Attribute

[英]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.

相关问题 使用System.Attribute类 - Using System.Attribute class 在System.Attribute中错误地实现了GetHashCode和Equals? - GetHashCode and Equals are implemented incorrectly in System.Attribute? 属性类,System.Attribute,复杂类型 - Attribute-Class, System.Attribute, Complex-Type 如何解决“无法将类型对象隐式转换为 System.Attribute”? - How to fix "Cannot implicitly convert type object to System.Attribute"? 如何在ashx文件上运行自定义System.Attribute - How to run a custom System.Attribute over an ashx file 无法将类型&#39;System.Attribute&#39;转换为通用参数&#39;T&#39;-为什么? - Cannot convert type 'System.Attribute' to generic argument 'T' - why? 使用RazorTemplates库时发生错误:&#39;CS0012:类型&#39;System.Attribute&#39;在未引用的程序集中定义&#39; - Error when using RazorTemplates library: 'CS0012: The type 'System.Attribute' is defined in an assembly that is not referenced' 投放从数据缓存中检索的列表时出现问题 - Problem casting a list retrieved from data cache 从 TempData 转换数据,系统 InvalidCastException - Casting data from TempData , System InvalidCastException 从System.XmlWriter投射到System.XmlTextWriter - Casting from System.XmlWriter to System.XmlTextWriter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM