如何将方法约束为返回类型:属性

本文关键字:返回类型 属性 约束 方法 | 更新日期: 2023-09-27 18:03:15

我有一个属性

[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' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint

示例使用从我的控制台:

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的子类,但我希望这是更有用的,无论如何,在罕见的情况下,你实际上使用继承的属性

这应该是:

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

typeof(T)改为输入typeGetCustomAttributes方法获取被调用类型的属性。