从C#中的另一个类调用该类中的方法 [英] Call method in class from another class in C#

查看:95
本文介绍了从C#中的另一个类调用该类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从另一个类(不是Main类)调用方法时,我遇到了一个小问题.这是我的测试代码:

I have a small problem when I'm trying to call method from another class (not Main class). Here's my testing code:

using System;

namespace ConsoleApplication3
{
    public class Program
    {
        static void Main(string[] args)
        {
            Class1 cl = new Class1();
            cl.TestMethod();
        }
    }

    public class Class1
    {
        public string TestMethod()
        {
            return "test";
        }
    }

    public class Class2
    {
        Class1 cl = new Class1();
        cl.TestMethod(); //Error here
    }
}

我应该怎么做才能在Class2中调用TestMethod?

What should I do to call TestMethod in Class2?

推荐答案

您不能从方法,构造函数或属性外部调用方法将第二类更改为此:

You can't call a method from outside a method,constrcutor or a property change class two to this:

public class Class2
{
    public Class2
    {
       Class1 cl = new Class1();
       cl.TestMethod(); //Error here
    }}

这篇关于从C#中的另一个类调用该类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆