开发者

How to assign same class object declared in 2 different namespaces

I have a webservice project with a class (let's refer to it as webservice.classA).

I have another class project producing a dll which references that class in its own namespace and instantiates an instance of it (lets call the dlls namespace dllnamespace).

In another project I want to access the member in the 开发者_开发百科dll

e.g.

using webservice;

namespace other_project
{
    class B
    {
        classA copy = null;
        //....
        dllnamespace.dostuff(); // amongst other things instantiates a classA object
        //....
        copy = dllnamespace.getclassA(); // method to return classA member

The compiler error I get is cannot convert type from dllnamespace.webservice.classA to other_project.webservice.classA

I guess I have a fundamental design flaw but I figure there must be (?) a way to declare/use "webservice.classA" in more than one namespace.


You have a name clash. The supported way of avoiding this (short of not naming your classes the same), is to define a using alias for one of the classes:

using webservice.classA = myWebserviceClassA;


You are right...the design flaw does exist in terms of naming.

Let us assume:

  • you have a class named MyClass

  • the class exists both in namespace- abc.xyz.qwe.tyu.MyClass

  • and in namespace - sed.qwe.dfg.ert.MyClass

The workaround is -

using NS1 = abc.xyz.qwe.tyu.MyClass;
using NS2 = sed.qwe.dfg.ert.MyClass;

This way you avoid the clash. Also, helpful to use if you have very long namespaces.

FURTHER REFERENCE : (From MSDN article on using Directive )

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

  • Create a using alias to make it easier to qualify an identifier to a namespace or type.

  • Create a using directive to use the types in a namespace without having to specify the namespace. A using directive does not give you access to any namespaces that are nested in the namespace you specify.


Change the copy definition line to:

dllnamespace.webservice.classA copy = null;


That's just the problem - you cannot have a class in more than one namespace. This is what namespaces were designed for - to prevent classes with the same name written by different people from aliasing. You'll need to decide for one of your namespaces to own that class and in the other one to import it. Alternatively if the dll and the web service are part of the same distributed app then they should use the same namespace.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜