从反射的方法c#中获取值

本文关键字:获取 反射的 方法 | 更新日期: 2023-09-27 17:59:52

在调用局部变量时,我可以从方法内部获取该变量的值。

我正在调用的方法调用另一个方法,并将我想要的值传递给它。有什么方法可以拦截那个调用或获取那个值吗。

这就是我的代码背后的想法:

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的调用会得到我想要的值,但我不知道是否可以这样做。

从反射的方法c#中获取值

带有BadMethod(int-ruinLife)的类是最终类吗?你能修改BadMethod函数的签名使其成为虚拟的吗?如果是这样,您可以用一个什么都不做的伪方法覆盖该方法。因此:

public class newClass : classIWant
{
    public newClass() : base()
    {
    }
    public override void BadMethod(int ruinLife)
    {
        // Do Nothing
    }
}

然后实例化你的类,而不是另一个类。请注意,只有当您可以使BadMethod成为虚拟的,或者它已经是虚拟的时,这才有效。否则,这种技术将不起作用,因为使用"new"而不是"override"是不起作用的。