Accessing variables from other namespaces

后端 未结 3 1581
无人及你
无人及你 2021-01-12 09:51

I am new to C# and programming in general my question is how do you call a variable that is in a different namespace? if I have this code

public void servic         


        
相关标签:
3条回答
  • 2021-01-12 10:16

    To add to Andy's answer you can also shorten the call to the MyInt property by adding this above the My.Namespace declaration:

    using My.Other.Namespace
    

    If you do that then your call to the MyInt property would look like this:

    int MyValue = MyOtherClass.MyInt
    
    0 讨论(0)
  • 2021-01-12 10:23

    Normally, variables don't live in a namespace alone, they live inside another class that could be in another namespace. If you need to access a variable in another class (in another namespace), your other class needs to expose the variable somehow. The common practice for this is to use a public Property (static if you only need access to that variable) for the variable.

    namespace My.Namespace
    {
        public class MyClassA
        {
            public void MyMethod()
            {
                // Use value from MyOtherClass
                int myValue = My.Other.Namespace.MyOtherClass.MyInt;
            }
        }
    }
    
    namespace My.Other.Namespace
    {
        public class MyOtherClass
        {
            private static int myInt;
            public static int MyInt
            {
                get {return myInt;}
                set {myInt = value;}
            }
    
            // Can also do this in C#3.0
            public static int MyOtherInt {get;set;}
        }
    }
    
    0 讨论(0)
  • 2021-01-12 10:29

    As a side node, it can be done by adding reference to the assembly in which the public members of another assembly are used. That's what incurred me.

    0 讨论(0)
提交回复
热议问题