如何在方法中获取前一个方法的参数? [英] How to obtain the parameters of the previous method in the method called ?

查看:66
本文介绍了如何在方法中获取前一个方法的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将参数传递给方法A并且在此方法中调用另一个方法B,则不传递参数。因为我可以在B方法中获得A方法的参数值。





- -------------------------------------------------- ------------------------------



If I pass parameters to a "Method A" and within this method call another "Method B" is not passed parameters. As I can get the values ​​of the parameters of the method of "A" in the "B " method.


---------------------------------------------------------------------------------

public class A{

	public void Method_A(string name){
	
		var b = new B();
		
		b.Method_B();
	}
}

public class B{

	public void Method_B(){	
	/*
		see parameter values of Method_A	
	*/	
	}
}



---------------------------------- -----------------------------------------------


---------------------------------------------------------------------------------

推荐答案

这是一个糟糕的主意。我可以编写Method_C并从中调用Method_B。您如何期望Method_B能够使用Method_C具有的任何参数?或者你想以某种方式检测是否从Method_A调用Method_B并且如果不是则抛出一个execption?







Method_A 必须将它的参数传递给Method_B。



你认为A级通过相当于Method_B到B类作为委托?或者B类需要一个事件?
That's a terrible idea. I could write Method_C and call Method_B from it. How can you expect Method_B to be able to use whatever parameters Method_C has? Or would you want to somehow detect whether or not Method_B was called from Method_A and throw an execption if it wasn't?



Method_A would have to pass it's parameters to Method_B.

Have you considered having class A pass the equivalent of Method_B to class B as a delegate? Or maybe class B needs an event?


我试图用有效的c#代码表达你的问题:

I'm trying to express your question in valid c# code:
void MethodA(int param) {
   MethodB();
}

void MethodB() {
   // You cannot access MethodA's parameter here
}





解决方案:

- 将参数传递给MethodB(但这意味着修改MethodB的签名):



Solution:
- Pass the parameter to MethodB (but that means modifying MethodB's signature):

void MethodA(int param) {
   MethodB(param);
}

void MethodB(int param) {
   // Here you can access param's value
}





- 使用方法之外的全局变量:


OR
- Use a global variable outside of your methods:

int _param;

void MethodA(int param) {
   _param = param;
   MethodB();
}

void MethodB() {
   // Here you can access _param which has been initialized with MethodA's parameter
}


ICorDebugILFrame https://msdn.microsoft.com/en-us/library/ms232990 [ ^ ]
ICorDebugILFrame https://msdn.microsoft.com/en-us/library/ms232990[^]


这篇关于如何在方法中获取前一个方法的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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