简体   繁体   English

从C#中的另一个类访问方法

[英]Accessing methods from another class in C#

I have a number of classes in a Classes file, and I want them all to be able to access the same, global method to save duplicating code. 我在Classes文件中有许多类,我希望它们都能够访问相同的全局方法来保存重复的代码。 Problem is, I can't seem to access a method from another class in my file - any ideas? 问题是,我似乎无法从我的文件中的另一个类访问一个方法 - 任何想法?

So my class1.cs layout is similar to this: 所以我的class1.cs布局与此类似:

public class Job1
{
    public Job1()
    {

    }
}

public class Methods
{
    public static void Method1()
    {
        //Want to access method here from Job1 
    }
}

You'll need to specify the class they are in. Like this: 你需要指定他们所在的类。像这样:

public Job1()
{
  Methods.Method1()
}

If the class Job1 is in a different namespace from Methods then you'll need to either add a using clause, or specify the the namespace when calling the method. 如果Job1类与Methods不同,那么您需要添加using子句,或者在调用方法时指定命名空间。 Name.Space.Methods.Method1()

Actually. 其实。 Public Job1(){} is a constructor and not a method. Public Job1(){}是构造函数而不是方法。 It can be called from main class by creating object form the JOB1 class. 它可以通过从JOB1类创建对象从主类调用。 Here add the following code: 这里添加以下代码:

public static void method1()
{
Job1 j1=new Job1();
}

constructor can be invoked by creating a object to the corressponding class.... 可以通过创建corressponding类的对象来调用构造函数....

To access methods of other classes, the methods must be static with a public Access modifier. 要访问其他类的方法,方法必须是静态的,具有公共Access修饰符。

static - Not bound to an instance of the class but shared by all other instances. static - 未绑定到类的实例,但由所有其他实例共享。

private - data can only be accessed from inside the same class. private - 数据只能从同一个类中访问。

public - data can be accessed from other classes but must be referenced. public - 数据可以从其他类访问,但必须引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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