c# - 从反射方法 C# 中获取值

标签 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. (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/

相关文章:

c# - 如何获取代码所在程序集的路径?

java - java类文件加载/链​​接/初始化阶段的查询

c# - 通过约定/反射动态地连接 View、Model 和 Presenter

c# - 选择的组合框项目待修复

reflection - 如何使用反射创建结构 slice ?

java - 如何获取该类中某个字段的字段值

c# - System.Drawing 图像在使用语句关闭后被锁定

c# - Array.ToString() 返回 System.Char[] c#

c# - 创下本地高分?

c# - 如何将 x.ToString() 传递到期望对象类型而不是仅仅 x 的方法中以防止装箱?