Frage

I don´t think that this question has (or can) been answered, or at least I didn´t find the answer: is it possible to create custom compile-time checks?

The specific situation is that I am programming a quantum spaces calculator, and while you could have vectors (1,0,0) and (1,0), I should modify certain operations between them as they belong to certain spaces. Even more, you could have (1,0) and (1,0) but neither of them belonging to the same spaces, so the operations between them would be different. But I don´t find a clever (not run-time) way to do this because they all belong to the same class so they have the same operators!

Also, the size of the vectors is arbitrary (from 0 to infinite) so I can´t make a class for all of them as a "Tuple".

War es hilfreich?

Lösung

You can try to use generics to prevent operations between different "vector" classes something like following concept code:

class Vector<Traits> : IEnumerable<double> 
{
    public static Vector<Traits> 
        operator + (Vector<Traits> left, Vector<Traits> right) { ... } 
}

var v1 = new Vector<MyTraitsOne>(2);    
var v2 = new Vector<MyTraitsOther>(2);

var r = v1 + v2; // should fail.

(Traits class as generic's parameter in sample is solely to distinguish different vectors of double, but in real case there may even be good usage of such class)

Andere Tipps

You can use Code Contracts to describe the non-trivial assumptions about class state and operations that are allowed on it. Some of the contracts can be checked at compile time, and others will generate a runtime exception.

Probably you want to look at unit tests. Not compile time, but pre-run-time checks on your cod. In your unit tests you'd specify the constraints your code should handle. And if a developer breaks these constraints, unit tests will fail, highlighting the problem.

People write books on unit-tests, so can't really write a lot about them, but you can start here: http://anthonyjbrown.blogspot.co.uk/2012/06/true-beginners-guide-to-unit-testing-in.html

As I already mentioned in my comment, I think you have more a modelling problem here than real problems with compile time checks.

But, as you ask, those checks might be achieved by leveraging something like postsharp.

Codeproject article on aspect oriented programming using Postsharp as a starter

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top