Using Attributes for Generic Constraints [duplicate]

我与影子孤独终老i 提交于 2019-11-30 11:23:40

No. You can only use (base)classes and interfaces as constraints.

You can however do something like this:

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.
}

No. You can only use classes, interfaces, class, struct, new(), and other type parameters as constraints.

If InsertableAttribute specifies [System.AttributeUsage(Inherited=true)], then you could create a dummy class like:

[InsertableAttribute]
public class HasInsertableAttribute {}

and then constrain your method like:

public static void Insert<T>(this IList<T> list, IList<T> items) where T : HasInsertableAttribute
{
}

Then T would always have the attribute even if it was only coming from the base class. Implementing classes would be able to "override" that attribute by specifying it on themselves.

No you can't. Your question is not about attributes, but object-oriented design. Please read the following to learn more about generic type constraint.

I rather suggest you do the following:

public interface IInsertable {
    void Insert();
}

public class Customer : IInsertable {
    public void Insert() {
        // TODO: Place your code for insertion here...
    }
}

So that the idea is to have a IInsertable interface, and implements this interface within a class whenever you want to be insertable. This way, you will automatically restrict the insertion for insertable elements.

This is a more flexible approach, and it shall give you the ease to persist whatever same or different information from an entity to another, as you have to implement the interface yourself within your class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!