Skip to main content
 首页 » 编程设计

c#之如何限制方法返回类型为 : Attribute

2024年02月13日13insus

我有一个属性

[System.AttributeUsage(System.AttributeTargets.Class] 
public class ModuleValues : System.Attribute 
{ 
    public Guid? Id { get; set; } 
 
    public ModuleValues(string id) 
    { 
        Id = Guid.Parse(id); 
    } 
} 

如何创建一个在找到属性后返回该属性的通用方法?

public static T GetAttribute<T>(Type type) where T : Attribute 
{ 
    object[] attrs = typeof(T).GetCustomAttributes(true); 
    foreach (Attribute attr in attrs) 
    { 
        if (attr.GetType() == typeof (T)) 
        { 
            //Console.WriteLine(attr.ToString()); 
            return attr as T; 
        } 
    } 
 
    return default(T); 
} 

有了约束,我的方法总是返回 null。

当我删除约束时,我可以找到带有 Console.WriteLine 的属性,但无法返回它,因为行 return attr as T; 给出了编译错误 The type parameter 'T'不能与“as”运算符一起使用,因为它既没有类类型约束也没有“类”约束

我的控制台的示例用法:

Assembly x = Assembly.GetAssembly(typeof(MyBase)); 
 
Type[] types = x.GetTypes(); 
foreach (Type type in types) 
{ 
    if (type.IsSubclassOf(typeof (MyBase))) 
    { 
        ModuleValues s = CustomAttributeHelper.GetAttribute<ModuleValues>(type); 
        Console.WriteLine("S" + s); 
    } 
} 

请您参考如下方法:

这一行是问题所在:

object[] attrs = typeof(T).GetCustomAttributes(true); 

您在 Type 上调用 GetCustomAttributes - 而不是您真正感兴趣的类型。您想要:

object[] attrs = type.GetCustomAttributes(true); 

或者更简单地说,将方法的其余部分替换为:

return (T) type.GetCustomAttributes(typeof(T), true).FirstOrDefault(); 

请注意,这也将选取作为 T 子类的属性,但我希望无论如何它都会更有用,在您实际对属性使用继承的极少数情况下。