c# - 将属性用于通用约束

标签 c# generics attributes extension-methods

<分区>

举个例子,比如..

public interface IInterface { }

public static void Insert<T>(this IList<T> list, IList<T> items) where T : IInterface
{
 // ... logic
}

这很好用,但我想知道是否可以使用属性作为约束。比如……

class InsertableAttribute : Attribute

public static void Insert<T>(this IList<T> list, IList<T> items) where T : [Insertable]
{
 // ... logic
}

显然这种语法不起作用,否则我不会发布问题。但我只是好奇这是否可能,以及如何去做。

最佳答案

不可以。您只能使用(基)类和接口(interface)作为约束。

但是你可以这样做:

public static void Insert<T>(this IList<T> list, IList<T> items)
{
    var attributes = typeof(T).GetCustomAttributes(typeof(InsertableAttribute), true);

    if (attributes.Length == 0)
        throw new ArgumentException("T does not have attribute InsertableAttribute");

    /// Logic.
}

关于c# - 将属性用于通用约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4146674/

相关文章:

asp.net-mvc - 如何为所有 Controller 编写 Action 过滤器

c# - char 对象对应于哪个字符编码(Unicode 版本)集?

c# - 通过Timer控制函数调用c#

c# - 将附加数据传递给 Blazor 组件中的通用 RenderFragment

java - 如何使用通配符实例化泛型?

python - 如何将属性添加到 ElementTree 中的 SubElement (Python)

c# - Unity3D_2019 : Adding EventTriggers at runtime

c# - WCF 代理生成 : svcutil. exe 与 wsdl.exe

c# - 通用表单的具体实现在设计器中不起作用

python - 有什么方法可以将变量传递给 django 元类?