简体   繁体   中英

Should I use Interfaces to enforce generics?

If I have the following generic interface:

    public interface IValidator<T>
    {
        Boolean IsValid(T entity_);
    }

Can I use it in the following manner? Is this against Object Oriented Programming guidelines?

    public PathValidator : IValidator<String>
    {
    }

Is that use of Interfaces against any sort of best practice?

No, this is fine and common (assuming that your interface is not empty and has a method signature like bool IsValid(T entity) ).

What makes you think it should be? If you let us know, we can elaborate.

当然不是,只需看看IList之类的通用集合接口即可。

If this is actually the body of the interface, it's generally not a good idea to have an interface with no contract (that is, it doesn't require you to implement any methods). Usually this is suggestive of a problem with your design.

An empty interface (Marker interface) is usually bad practice because you should use an Attribute instead.

But if it's only empty because you omitted it to simplify the example then it looks perfectly fine to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM