如何将一个方法的局部变量访问到c#中同一个类的其他方法 [英] how to access a local variable of one method into other method in same class in c#

查看:637
本文介绍了如何将一个方法的局部变量访问到c#中同一个类的其他方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Windows应用程序中的c#中将一个方法的局部变量访问到同一类中的其他方法。



是否可能?

how to access a local variable of one method into other method in same class in c# in windows application.

Is it possible??

推荐答案

Noup,局部变量只能在其范围内访问。当他们的他们的方法暂时不执行时,他们就生活在堆栈上而根本不存在。



你必须将你的变量提升到成员级别从不同的方法访问它。
Noup, local variables are only accessible from within their scope. They live on the stack and simply don't exist when "their" method is not executed at the moment.

You will have to promote your variable to member level to access it from different methods.


我能想到的最接近你的问题的是 ref - 方法中的参数电话:

The closest thing that somehow relates to your question that I can think of are ref-Parameters in method calls:
void SomeMethod()
{
    int x = 1;
    SomeOtherMethod(ref x);
    // at this point x==2
}

void SomeOtherMethod(ref int a)
{
    a = 2;
}



如你所见, ref -Parameters允许被调用的方法修改值调用方法范围内的变量。但是没有从SomeMethod()调用的其他方法无法修改 x 的值。



大量使用 ref - 参数通常是不好的做法,在使用之前你应该三思。


As you can see, ref-Parameters allow the called method to modify the value of a variable within the calling method's scope. But other methods that aren't called from SomeMethod() have no way to modify the value of x.

Heavy use of ref-Parameters is generally bad practice, you should think twice before using it.


这篇关于如何将一个方法的局部变量访问到c#中同一个类的其他方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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