I need to define an Interface which has to enforce certain operator overloading to the types which implements it. There doesn't seem an obvious way to do it since operator overloading has to be done using static methods in class. Is there any way to achieve the same effect (using abstract classes or anything else)?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Since its operator can only be overloaded and not overridden its quite difficult. The best solution I can think of is use an abstract class and overloading like this.
You could implement the overloading in an abstract base class, but delegate the actually operation specifics to an abstract method. Then this will have to be implemented and the overloading will be don with their implementation.
Though I'm not sure if this is complete.
Bit of a hack, but...
You could provide operator overloads in your base class that then call some published abstract methods in one of the classes to do the job there.
No. The only sensible way to do this would be to have a unit test check use reflection to find all concrete implementations, and then verify this condition. You could also perhaps do something at runtime re the same via a static constructor, but then the question is which static constructor?
Another approach is to drop the operators and use an interface-based approach; for example , if you need
T
to have+(T,T)
then instead of operators have an interface with anAdd(T)
method. Another advantage here is that interfaces are usable from generics (typically via constraints), where-as using operators from generic code takes some effort.I have done this in the past...
And then implemented as follows: