質問

I'm a beginner in C#. I want to do the following:

Having class A in namespace nA I need to implement class B in namespace nB that inherits everything from A and adds some functionality, that's fine.

In ProjectA I have:

namespace nA{
    public abstract class A{
        public const int a = 1;
    }
}

in ProjectB t I have:

using ProjectA.nA;
namespace nB{
    class abstract B : A{
        public const int b = 2; 
    }
}

and in ProjectC I have

using ProjectB.nB;
namespace nC{
    class C{
        void someMethod(){
            int valueA = B.a //error, nB.B does not contain a definition for 'a'
            int valueB = B.b //works just fine
        }
    }
}
役に立ちましたか?

解決

Since it should work, I would suggest that you check you're not missing any assembly references in your projects.

他のヒント

Constants and static members are always accessed via the class that actually defines thems. A.a will work. Also note that it is accessible from any class, not just an inheritor.

In project B write:

using ProjectA.nA;
namespace nB{
    class abstract B : A{
        public const int a = A.a; 
        public const int b = 2; 
    }
}

Then project C should compile. Or one could do:

using ProjectB.nB;
namespace nC{
    class C{
        void someMethod(){
            int valueA = ProjectA.nA.a;
            int valueB = B.b;
        }
    }
}

Since ProjectC will have to reference ProjectA.

The better lesson here is to think in terms of separation of concerns. If class C should not know directly about class A, then it should also not now about a constant class A defines. Instead, there should be some functionality in B which uses the constant and makes sense for what class B is attempting to accomplish. Hence, what class B is concerned with that uses class A and provides this appropriate separation.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top