开发者

Using Attributes for Generic Constraints [duplicate]

This question already has answers here: 开发者_运维百科 Can you use "where" to require an attribute in c#? (5 answers) Closed 9 years ago.

Given an example such as ..

public interface IInterface { }

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

This works fine, but I was wondering if it is possible to use an Attribute as a constraint. Such as ...

class InsertableAttribute : Attribute

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

Obviously this syntax doesn't work, or I wouldn't be posting the question. But I'm just curious if it is possible or not, and how to do it.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜