简体   繁体   中英

Access public partial class variable in another class

I have a class with following structure :-

namespace CL.Forms
{
    public partial class A
    {
        public StringBuilder sb = new StringBuilder();

        sb.Append("a");
        sb.Append("b");
    }

    public class B
    {
        A objA=new A();
        string s= objA.sb.ToString();
    }
}

I want to access the varible in class A from class B . I tried the above method. But it doesn't work. Anyone knows the answer. Please help me.

You need to create a constructor or method

namespace CL.Forms
{
    public partial class A
    {
        public StringBuilder sb = new StringBuilder();

       //Constructor to set default for string builder
        public A()
        {
            sb.Append("a");
            sb.Append("b");
        }
    }

    public class B
    {
        public B()
        {
            A objA=new A();
            string s= objA.sb.ToString();
        }
   }

You need to put your code(s) inside of a method, like constructor:

public partial class A
{
    public StringBuilder sb = new StringBuilder();

    public A()
    {
       sb.Append("a");
       sb.Append("b");
    }
}

public class B
{
    A objA = new A();
    public B() 
    {
        string s = objA.sb.ToString();
    }
}
namespace CL.Forms
{
    public partial class A
    {
        //decalring sb
        public StringBuilder sb = new StringBuilder();
        //giving sb default values incase you dont change it just call the variable but it has
        //but it has to happen in a method
        public A()
        {
            sb.Append("a");
            sb.Append("b");
        }
        // a seperate methode to return sb
        public StringBuilder getSb()
        {
            return sb;
        }
    }
    public static class B
    {
        //same stuff
        A objA = new A();
        public void methodNameHere()
        {
            string s = objA.sb.ToString();
        }
    }
}

try this, you forgot to implement methodes in your classes. that is crucial else it wont work. But maybe it is better if you just google some tutorials for OOP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM