访问同一类中的两个方法 [英] Access two methods in same class

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

问题描述

public class classA
{

    public void MethodA()
    {
        Console.Write("Raised in MethodA");
    }
    public void MethodB()
    {
        Console.Write("Raised in MethodB");
    }
}







我想要访问这两种方法,比如




I want to access these two methods like

(new classA()).MethodA().MethodB();





是否有可能扩展方法正常工作y不正常Class



Is it possible Extension Methods are working like that y not normal Class

推荐答案

1.TheThe类名应该是大写的:ClassA;



2.你的代码不起作用,为了能使你的方法MethodA必须返回你的班级ClassA,所以在你的方法中你应该有下一个代码:返回这个;返回当前对象。
1.The class name should be with uppercase: "ClassA";

2.Your code will not work, in order to can work your method "MethodA" have to return your class "ClassA", so in your method you should have the next code: "return this;" to return the current object.


您提供的表达式不起作用(也不适用于扩展方法),除非 MethodA 返回 classA ,但在这种情况下,它没有 - 它的返回类型是 void



我不知道你为什么要那样打电话给他们。我建议将新的classA存储在变量中,并调用如下方法:

The expression you provided doesn't work (also not for extension methods), unless MethodA returns a classA, but in this case, it doesn't -- its return type is void.

I don't know why you want to call them that way. I'd suggest to store the new classA in a variable, and call the methods like this:
classA a = new classA();
a.MethodA();
a.MethodB();



如果你真的想使用那个表达式,请使用 MethodA 返回,其类型为 classA 。 (也许 MethodB 也应该这样做,如果你想让你的表达更长):


If you really want to use that expression, make MethodA return this, which has classA as type. (and perhaps MethodB should do the same, if you want to make your expression longer):

public class classA
{
    public classA MethodA()
    {
        Console.Write("Raised in MethodA");
        return this;
    }
    public classA MethodB()
    {
        Console.Write("Raised in MethodB");
        return this;
    }
}



使用上面的类,你的表达式可以工作。


With the above class, your expression works.


你可以通过返回对象的实例来实现该目标,而不是 void 。类似于:

public class classA
{
 
    public classA MethodA()
    {
        Console.Write("Raised in MethodA");

        return this;
    }
    public classA MethodB()
    {
        Console.Write("Raised in MethodB");

        return this;
    }
}


这篇关于访问同一类中的两个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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