How to see which “using” is used in Visual Studio

2019-07-17 04:50发布

This question already has an answer here:

How can I see which using statements provides a class in Visual Studio 2013?

And how can I detect conflicts?

I have this kind of code

foo.cs:

namespace foo
{
    class XmlConverter 
    {
    }
}

bar.cs:

namespace bar
{
    class XmlConverter 
    {
    }
}

And I need to use both foo and bar namespaces (both have multiple classes).

EDIT: I know I can rename my classes (or use aliases) but how can I detect this issue(wrong class being used) ? Is it even possible ?

2条回答
Anthone
2楼-- · 2019-07-17 05:26

You can use using aliases for this. Syntax looks like this: using MyAlias = MyNamespace.A.

See Using alias directives and/or How to: Use the Global Namespace Alias

In your case:

using FooConverter = foo;
using BarConverter = bar;

public ThirdPartyClass
{
     public void SomeMethod(FooConvert.XMLConverter fooConv, BarConverter.XMLConverter barConv)
     {
     }
}

of course that only makes sense when your actual namespace consists out of at least two parts or the name of the namespace is much longer and could be shortened without losing readability.

For example shorten System.IO to SysIO or ThisIsMyNamespace to MyNamespace. Else it's just more yping. With your example it makes more sense to just not have a using statement.

What is not possible is to somehow have the compiler 'detect' whether you are using foo's XMLConverter or bar's XMLConverter without putting some kind of classifier (be it alias or entire namespace) in front of the classname.

To OP's update: The compiler will let you know that something is wrong. The message is Class1 is an ambiguous reference between Foo.Class1 and Bar.Class1.

查看更多
在下西门庆
3楼-- · 2019-07-17 05:31

If there is a conflict then the C# will complain with an error. In this case your code should use a fully qualified name as in new foo.XmlConverter or new bar.XmlConverter.

However this is bad practice. If you can you should rename classes to FooXmlConverter and BarXmlConverter.

查看更多
登录 后发表回答