Is there a way to check if my element with elementtype class has a certain other class in his inheritance hierarchy?
My usecase is: I have to check if my Exceptions are prefixed with "Exception". To do so, i have to somehow determine if a certain class is an exception. The onl开发者_JAVA百科y way i can be sure is if it is inherited by the Exception class itself.
Checking the baseclass type for being an exception is easy enough, but imagine the following scenario:
class GenericMathException : Exception{}
class SpecificMathException : GenericMathException{}
The only information i can get about the SpecificMathException
is that it's baseclass type is GenericMathException
, but i can't go any further up in it's inheritance hierarchy.
The usual approach of reflection can't be used too, afaik.
So, anyone ever had to deal with this problem and found a solution? Or has any alternative approach to identify Exceptions?
Thanks in advance.
By its nature, StyleCop indeed works only with the contents of the file and can not use information from the assembly itself.
But, if you ask about "alternative approach to identify Exceptions", there is a rule in StyleCop+ which performs a checking very close to yours. You specify a list of base classes (Attribute
, Exception
, EventArgs
and Stream
by default), and it ensures that all classes inherited from them have the name that ends with ...Attribute
, ...Exception
and so on.
The checking works in the following way. If the name of the base class ends with a string from the list, it ensures that the name of the inherited class should also end with the same string. E.g., if it meets Class2 : InvalidOperationException
or Class2 : SomeUnknownException
, it will raise a violation in both cases.
Assuming that you follow this rule, all your inherited classes will always be named well, even if they are multi-inherited. The only thing that can not be checked in this way, is the situation where you deal with some classes not from "yours" assembly, that already have broken this rule. E.g., if some assembly has Class2 : Exception
, and you reference this assembly as a binary (and do not have a chance to check it with StyleCop) then you will not be able to check if your Class3
inherited from Class2
should be prefixed with ...Exception
.
But practice shows that the last issue is rather rare, so the method described above works really well for StyleCop.
精彩评论