Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

c# - How do I reference a Using Alias Directive from another class/file

I have a using alias directive to alias a complex type for readability.

namespace MyNamespace
{
    using ColorMap = SortedDictionary<float, Color>;

    public class Foo
    {
        public ColorMap colors = new ColorMap();

        ...
    }
}

In another file (the test for this class), I have:

namespace MyNamespace.Tests
{
    public class TestFoo
    {

        [Fact]
        public void TestFooCtor()
        {
            SortedDirctionary<float, Color> colorMap = 
                new SortedDirctionary<float, Color>

            // Want to be able to just do this:
            //ColorMap colorMap = new ColorMap();

            ...
        }
    }
}

Is there any way reference ColorMap from my test without repeating myself with another using directive?

It seems like I should be able to do MyNamespace.ColorMap? Really, I wish I could make this "typedef" owned by the class Foo, and then be able to reference it by saying Foo.ColorMap. Neither seem possible in C#? How do I do C++ style typedefs that can be used in client code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No you cant do this

using directive (C# Reference)

The scope of a using directive is limited to the file in which it appears.

Further clarification in

Namespaces - C# language specifications

Given

namespace N3
{
    using R = N1.N2;
}

namespace N3
{
    class B: R.A {}            // Error, R unknown
}

the scope of the using_alias_directive that introduces R only extends to member declarations in the namespace body in which it is contained, so R is unknown in the second namespace declaration.

In short, they are only valid in the enclosing compilation unit or immediate namespace they are declared, and are limited to the file they exist in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...