How to handle same class name in different namespaces?

梦想的初衷 提交于 2019-11-29 01:12:37

If i do that i will then need to specify the full namespace name before my static class in order to access it?

No, there is no need for that, though the details depend on the class that will use these types and the using declarations it has.

If you only use one of the namespaces in the class, there is no ambiguity and you can go ahead and use the type.

If you use both of the namespaces, you will either have to fully qualify the usages, or use namespace/type aliases to disambiguate the types.

using ERPUtils = MyCompany.ERP.Utilities;
using BCUtils = MyCompany.Barcode.Utilities;

public void MyMethod()
{
  var a = ERPUtils.Method();
  var b = BCUtils.Method();
}

There isn't any other way. You can make an aliases in using directives:

using MC=MyCompany.ERP;
using MB=MyCompany.Barcode;
...
public void Test()
{
  var a = MC.Utilities.Method();
  var b = MB.Utilities.Method();
}

It's the simplest way to manage them.

The MS guidelines have the following to say:

Do not introduce generic type names such as Element, Node, Log, and Message. There is a very high probability it would lead to type name conflicts in common scenarios.

and

Do not give the same name to types in namespaces within a single application model.

I concur that it's probably a good idea to use BarcodeUtilities and ErpUtilities instead. (Unless the utility classes are not meant to be used by client code, in which case you could name them Utilities and make them internal.)

"Utilities" is not a very good name for a class, since it is far too generic. Therefore, I think you should rename both of them to something more informative.

You can use an alias:

using BarcodeUtils  =  MyCompany.Barcode.Utilities;

on the pages you have clashes. But ideally rename them if this is happening in a lot of places.

I would suggest using different class names. If you really want to call both of them Utilities then you could use the alias feature on the using directive, e.g.

using ERP = MyCompany.ERP;
using Barcode = MyCompany.Barcode;

...
    ERP.Utilities.SomeMethod();
    Barcode.Utilities.SomeMethod();

You will have to use the full path when both are named the same. Otherwise you will get an ambiguous reference error.

You can use an alias however that will save you some typing:

using Project = PC.MyCompany.Project;

I would go for a different name that's somewhat more descriptive. A

It actually depends on the purpose of your classes. If you are going to distribute your Barcode.Utilities and ERP.Utilies seperately it is better stay like this. On the other hand, if you are going to use them only in same class, you may use 2. method for easiness of code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!