我可以在调用方法时从方法内部获取局部变量的值。
我正在调用的方法调用另一个方法并将我想要的值传递给它。有什么方法可以拦截该调用或获取该值。
这是我的代码背后的想法:
namespace test
{
class main
{
public static int Main(string [] args)
{
//This gives my the type of class I want since it is private. (this does work)
Type classTypeIWant = typeof(otherNamespace.someClassInThatNameSpace).Assembly.GetTypes()
.FirstOrDefault(t => t.Name == "ClassIWant");
//This creates an instance of the class I want using the default constructor
object classInstanceIWant = Activator.CreateInstance(classTypeIWant);
//Invoke the method
int resultINeed = classTypeIWant.GetMethod("MethodIWant")
.Invoke(classInstanceIWant, null));
}
}
}
namespace otherNamespace
{
public class someClassInThatNameSpace{}
private class classIWant
{
public classIWant
{
//stuff happens
}
public void BadMethod(int ruinLife)
{
//do stuff
//ruin value I want
return ruinedValue;
}
public int MethodIWant()
{
//this is the value I want to grab
int valueIWant = 10;
//but this method faults because of things I cannot change (I really cannot change this)
int valueIDontWont = BadMethod(valueIWant);
//it will not make it here because of BadMethod
return valueIDontWant;
}
}
}
拦截对 BadMethod 的调用会给出我正在寻找的值,但我不知道是否可以这样做。
最佳答案
带有 BadMethod(int ruinLife) 的类是最终类吗?并且您可以修改 BadMethod 函数的签名以使其成为虚拟的吗?如果是这样,您可以使用不执行任何操作的虚拟方法来覆盖该方法。所以:
public class newClass : classIWant
{
public newClass() : base()
{
}
public override void BadMethod(int ruinLife)
{
// Do Nothing
}
}
然后只需实例化您的类而不是其他类。请注意,这仅在您可以将 BadMethod 设为虚拟或者它已经是虚拟的情况下才有效。否则,此技术将不起作用,因为使用"new"而不是“覆盖”将不起作用。
关于c# - 从反射方法 C# 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31061931/