简体   繁体   中英

Nested classes don't have a namespace

I am writing a custom FxCop-rule which checks if Exceptionclasses inherit from the correct Exception-namespaces. This check itself works perfectly. But, in my testcase, I came across something weird.

namespace MyNamespace.IO
{
    [TestClass]
    public class ExceptionsShouldOnlyInheritFromCorrectNamespacesTests
    {
        [TestMethod]
        public void TestExceptionInheritanceNamespace()
        {
            RuleAssert.AssertProblemsAreEqualToExpectedProblems<ExceptionsShouldOnlyInheritFromCorrectNamespaces, ExceptionInhertTestClass>();
        }    
    }

    namespace Something
    {
        [CaRuleTestClass]
        public class ExceptionInhertTestClass
        {
            public class MyFirstException : SystemException
            {                   
            }

            public class MySecondException : FileNotFoundException
            {                   
            }

            [ExpectedProblem]
            public class MyWrongException : AbandonedMutexException
            {                   
            }
        }
    }
}

The above code demonstrates the setup. As you can see I have a nested-namespace (this is only for testpurposes). In this there is one main class ExceptionInhertTestClass which holds three testclasses that are run by the custom FxCop-rule.

This custom rule checks the namespace of the class and compares it to the class it inherits from.

When debugging the rule, I noticed that the there was an unexpected problem on the MySecondException -class. There was no Namespace found for this class, at all. The picture demonstrates:

图片

Why does the class not have a value for its' namespace-property, while it obviously should have?

Actually, it's arguable whether it should have a namespace or not. According to the .NET CLI spec , the metadata for a nested type should actually have a null namespace (see point 11 on p.223). That said, the FxCop API doesn't necessarily need to expose metadata in a way that corresponds to the spec. However, since Microsoft doesn't provide an SDK for FxCop rule creation, there is no way to know what might have been intended here.

In other words, now that you know that the namespace for a nested type isn't exposed in this way, you should climb its declaration hierarchy to find the appropriate namespace if you need it. :)

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