开发者

How to make an object belong to a namespace (VS 2008)?

I have a name space Company.Controls, which contains several controls. I also have a class called "Common" which contains enums/structures/static methods that I use throughout the controls.

Is there a way to make these "Common" peices belong to the Company.Controls namespace this way I don't have to keep typing "Common.Structure"? Essentially having he "Common" 开发者_运维知识库both a namespace and a class.

Just seems messy and confusing when reading the code.

example (all the other controls are in the Blah.Controls.Common namespace)

namespace Blah.Controls
{
    public enum ControlTouchState
    {
        Down = 0x00,
        Up = 0x01,
    }

    public Common()
    {
      //Stuff here
    }

}

Thanks.


You can't get exactly what you want; in C# all methods have to be in a class.

Depending on what is in your Common class, you might be able to find something a slightly more satisfying by using extension methods:

namespace Blah.Controls
{
    public class CommonControl { }

    public static class Common
    {
        public static void Foo(this CommonControl cc) { }
    }

    public class Control1 : CommonControl
    {
        public void Bar()
        {
            this.Foo();
        }
    }
}

Another thing you might consider is using partial classes which would let you write simple wrappers elsewhere:

namespace Blop.Controls
{
    public static class Common
    {
        public static void Foo() { }
    }

    public partial class Control1
    {
        public void Bar()
        {
            Foo();
        }
    }

    public partial class Control1
    {
        public void Foo()
        {
            Common.Foo();
        }
    }
} 

Obviously, introducing some inheritence could eliminate some of the duplication; I'm assuming you don't want to do that.


Is there some reason that the nested types in Common MUST be nested? Why not separate them out into their own namespace?

namespace Common
{
    public struct Structure 
    {
        // ... 
    }

    public enum Enumeration
    {
        // ...
    }

    public class Common
    {
        // ...
    }
}

You could then use the Common namespace as such:

namespace Blah.Controls
{
    using Common;

    class Control
    {
        Struct myStruct;
        Enumeration myEnum;
        Common myCommon; // references the class, not the namespace
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜