简体   繁体   English

如何从另一个类实例调用一个类方法

[英]How to call a class method from another class instance

I'm new to C# , I'm in doubt about how to make this work: 我是C#新手,我对如何实现此功能有疑问:

namespace Core {
    public class A{
        private reandonly string _var;
        public A(string var){
            _var=var
        }
        public GetValue() => return _var;
    }
}

using System;
namespace Core.Resources {
    public static class B{
        public static void DoSomething(){
            Console.Writeline($"{A.GetValue()}");
        }
    }
}

public class C{
    static void Main(string args[]){
        A a = new A("name");
        a.Resources.B.DoSomething();
    }
}

A is in main folder, B is in Main/Resources folder, together they make a classlib, Program.cs is using this lib. A在主文件夹中, BMain/Resources文件夹中,它们一起构成一个类库, Program.cs使用此库。 Is there a way to make this work? 有没有办法使这项工作?

If you write a.Resources you are basically trying to retrieve the member Resources of the class A , which is obviously not defined. 如果编写a.Resources ,则基本上是在尝试检索类A的成员Resources ,这显然是未定义的。 Since B is a static class defined in the Core.Resources namespace, all you have to do is to change your code as follows: 由于B是在Core.Resources命名空间中定义的静态类,因此您要做的就是如下更改代码:

public class C
{
    public static void Main(string args[])
    {
        A a = new A("A");
        Core.Resources.B.DoSomething();
    }
}

or, alternatively, if you don't want to reference the namespace every time: 或者,或者,如果您不想每次都引用命名空间:

using Core.Resources;

public class C
{
    public static void Main(string args[])
    {
        A a = new A("A");
        B.DoSomething();
    }
}

Note that if yuu explicitly define a public constructor for A that accepts one or more arguments, the default parameterless constructor is no more available... hence you have to pass a string to the A constructor if you don't want to see an error in your console. 请注意,如果yuu为A显式定义一个接受一个或多个参数的公共构造函数,则默认的无参数构造函数将不再可用...因此,如果您不想看到错误,则必须将字符串传递给A构造函数在您的控制台中。 Alternatively, you have to rewrite your A class so that it implements a default parameterless compiler, for example: 或者,您必须重写A类,以便它实现默认的无参数编译器,例如:

public class A
{
    private reandonly String _var;

    public A() : this(String.Empty) { }

    public A(String var)
    {
        _var = var;
    }
}

EDIT AS PER OP COMMENTS AND QUESTION CHANGES 根据操作注释和问题更改进行编辑

public class A
{
    private reandonly String _var;

    public String Var
    {
        get { return _var; }
    }

    public A(String var)
    {
        _var = var;
    }
}

public static class B
{
    public static void DoSomething(String text)
    {
        Console.Writeline(text);
    }
}

public class C
{
    public static void Main(string args[])
    {
        A a = new A("name");
        B.DoSomething(a.Var);
    }
}

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

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