C# 从方法c中获取值#
调用局部变量时,我可以从方法内部获取该变量的值 我调用的方法调用另一个方法并将我想要的值传递给它。我有没有办法截获那个呼叫或获取那个值 这就是我的代码背后的想法:C# 从方法c中获取值#,c#,reflection,C#,Reflection,调用局部变量时,我可以从方法内部获取该变量的值 我调用的方法调用另一个方法并将我想要的值传递给它。我有没有办法截获那个呼叫或获取那个值 这就是我的代码背后的想法: namespace test { class main { public static int Main(string [] args) { //This gives my the type of class I want since it is private.
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)的类是final吗?您可以修改BadMethod函数的签名使其成为虚拟的吗?如果是这样,您可以用一个不做任何事情的伪方法重写该方法。因此:
public class newClass : classIWant
{
public newClass() : base()
{
}
public override void BadMethod(int ruinLife)
{
// Do Nothing
}
}
然后只是实例化您的类,而不是另一个类。请注意,只有当您可以将BadMethod设置为虚拟,或者它已经是虚拟的时,这才有效。如果没有,这项技术将不起作用,因为使用“new”而不是“override”将不起作用。你能从classIWant继承吗?如果
BadMethod
不是virtual
你就不走运了。。。反编译/重写IL可能更快…如果valueIWant在这种情况下是一个常量值(即10),则无法获得该值。但是,如果valueIWant从任何其他来源(如类或文本框等)获取其值,则您应该能够复制相同的值以获取该值。但是,这会导致重复的代码。简单的回答是,不,你不能从函数内部得到一个值。你怎么知道它有你想要的?你能描述一下你有能力改变哪些代码吗?我可以想到很多选择,但它们都涉及到更改代码的不同部分,而且不清楚哪些更改对您可用。问题是该类是私有的,所以我不能仅仅扩展它。虽然该方法不是最终的,但我是否可以使用它?如果无法将其从private更改为public,那么您就无能为力(据我所知)。如果担心该类对其他程序集可见,您可能会将该类更改为internal而不是private,但这会使继承稍微复杂化,因为如果继承类位于另一个程序集中,则必须尝试添加[assembly:InternalsVisibleTo(“newAssembly”)]之类的内容,但老实说,我不能100%确定是否允许您在另一个程序集中实际继承。