c#从另一个方法引用一个方法的变量
本文关键字:方法 一个 变量 另一个 引用 | 更新日期: 2023-09-27 18:08:02
有时我想在方法B中使用很多Method As变量。通常将所有变量传递给这个方法是相当痛苦的,特别是如果我必须多次这样做(但不能简单地复制粘贴,因为有些东西会改变),或者我只是太懒了。
有没有像"内部方法"这样的东西?或者一些简单的方法来处理这个问题?
我想做什么:
public void A()
{
int a = 4;
string b = "Hello World";
B(ref vals);
//Or like so
C(ref current);
}
public void B(ref AllValues)
{
a = 3;
...
}
public void C(ref MethodThatSharesAllValues method)
{
method.a = 3;
...
}
如果它们都在同一个类
你可以将它们配置为类变量:
public class MyClass{
//set this as private/protected/public or nothing and you can also set a default value
int a;
public void A()
{
a = 4;
string b = "Hello World";
B();
C();
}
public void B()
{
a = 3;
...
}
public void C()
{
a = 3;
...
}
}
<标题> Elseway h1> 在可以从方法B访问MyClassA
int myExValueA = MyClassA.a;
否则你必须将它们作为参数传递
希望能有所帮助
标题>你可以创建一个类来保存你的参数,然后只传递这个类的一个实例
public void metA(Parameters input)
{
input.a = 5;
input.c = "hello";
metB(input);
}
public void metB(Parameters input)
{
input.b = 10;
}
public class Parameters
{
public int a;
public int b;
public string c;
}
你可以在类头文件中声明这些变量是静态的,并按照你喜欢的方式使用它们,如果它们在同一个类中是私有的,对于子类是受保护的,否则是内部的或公共的。或者像这样将变量框在类中:
public class Foo
{
public int A { get; set; }
public int B { get; set; }
public string C { get; set; }
}
如果传递的变量是相同的类型,您可以使用像int[]或string[]或List
类似如下:
public void foo() {
int a = 10;
// ...
}
public void foo_bar() {
// "a" is not in scope for foo_bar, so this won't compile
a = 20;
// ...
}
肯定是无效的。我不认为这是你在你的问题中想要的。
你可以做一些类似于你要求使用闭包的事情,但是它们有点棘手。基本上,像这样的东西是有效的(我不是坐在IDE前面,所以如果语法有点不对劲,请原谅我):
Func<int> GetCounter() {
int count = 0;
// This will capture the count variable from its context
Func<int> method = () => ++count;
return method;
}
虽然相当多的语言(包括一些版本的c++现在我猜)都有闭包(或一些类似的变体),但它们在不同语言之间的工作方式似乎几乎没有一致性(例如,"count"变量是否应该在捕获后不可变),所以检查你正在使用的语言的文档(在这种情况下,c#)以准确理解它们是如何工作的很重要。
就我提供的第一个代码示例而言,我怀疑这就是您所要求的,但是作为一个简短的题外话,您可能真的不希望它是允许的(并且我再次怀疑这不是您所要求的语法/语义),因为它会很快导致意外/未定义的行为。例如:
- 如果你有一个在
Foo()
中初始化的局部变量a
,并且在运行Foo()
之前在Foo_Bar()
中引用它,它的值应该是多少? - 如果你运行Foo()来初始化变量,在Foo_Bar()中编辑变量,然后再次运行Foo(),你应该重新初始化变量还是允许它保持Foo_Bar()设置它?
- 在方法调用完成后对局部变量进行垃圾收集是否安全,或者可能会再次引用它?
参见以下内容:
public class SomeObject
{
public int SomeProperty { get; set; } = 6;
// ...
}
public class SomeOtherObject
{
// ..
}
void foo() {
// What is the content of "a" before foo() runs?
object a = new SomeObject();
// Which "a" should this refer to - the one in foo() or the one in foo_bar()?
// Also, is this a valid cast given that we haven't specified that SomeOtherObject can be cast to SomeObject?
var b = (SomeObject)a;
// If we run foo() again, should "b" retain the value of SetProperty or set it back to the initial value (6)?
b.SetProperty = 10;
// ...
// Is it safe to garbage collect "a" at this point (or will foo_bar refer to it)?
}
void foo_bar() {
object a = new SomeOtherObject();
// ...
}