How to initialize an object from one method to ano

2020-07-26 02:47发布

In a class, I have 2 methods. In method1 I created an object, but I can't use the same object in method2.

Why? Please help with a simple example.

The coding is too big, so I have given the layout

public class Sub
{
}

public class DataLoader
{
    public void process1()
    {
        Sub obj = new Sub();
    }

    public void process2()
    {
        // here I can't use the object
    }
}

标签: c# class methods
4条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-26 03:03

You should use member variables in your class.

public class DataLoader
{
    private Sub mySub;

    public void Process1()
    {
        mySub = new Sub();
    }

    public void Process2()
    {
        if(mySub == null) 
            throw new InvalidOperationException("Called Process2 before Process1!");            

        // use mySub here
    }
}

Read up on different variable scopes (specifically, instance variables in this case). You can also pass your object as a parameter, like codesparkle mentioned in their answer.

查看更多
三岁会撩人
3楼-- · 2020-07-26 03:12

You have to set the object as a class field, then you can access it from every method of your class.

查看更多
放我归山
4楼-- · 2020-07-26 03:13

The short answer (without seeing your code) is that the object created in Method1 doesn't have any visibility, or scope, in Method2.

There are already some good answers here that show you how to solve your specific problem. But the real answer here is to familiarize yourself generally with the concept of Scope. It's a fundamental part of programming and learning more about it will help you tons.

There are many good articles and videos on the subject. This video is a great start. Good luck!

查看更多
Evening l夕情丶
5楼-- · 2020-07-26 03:20

The reason why this isn't working is scope. A local variable can only be accessed from the block it is declared in. To access it from multiple methods, add a field or pass it to the other method as a parameter.

Field:

class YourClass
{
    object yourObject;

    void Method1()
    {
        yourObject = new object();
    }

    void Method2()
    {
        int x = yourObject.GetHashCode();
    }
}

Parameter:

class YourClass
{
    void Method1()
    {
        Method2(new object());
    }

    void Method2(object theObject)
    {
        int x = theObject.GetHashCode();
    }
}
查看更多
登录 后发表回答