【问题标题】:Getting wrong return values when using reflection to call a static method?使用反射调用静态方法时得到错误的返回值?
【发布时间】:2011-03-29 21:12:20
【问题描述】:

我有 2 种类型,称为 EffectEffectMethods,这是我正在调用的方法的静态类:

public class EffectMethods
{
    public static EffectResult Blend (Effect effect)
    {
        bool success = true;
        return new EffectResult ( effect.Type, success );
    }
}

我找到了正确的方法:

Type.GetMethods ( BindingFlags.Public | BindingFlags.Static );

并过滤掉正确的。

但是当我调用它时:

( EffectResult ) method.Invoke ( null, new object [ ] { this } );
public class Effect
{
    public EffectResult Apply()
    {
        var methods = Type.GetMethods ( BindingFlags.Public | BindingFlags.Static );
        var method = methods.First ( ... );

        // This result value is now different (success = false)
        return ( EffectResult ) method.Invoke ( null, new object [ ] { this } );
    }
}

我得到了错误的结果。这里thisEffect 的当前实例,因为它是包含反射调用的类型。

基本上我计算的值之一是返回操作是否成功的标志。但是这个值在代码中设置为true,但是方法通过反射返回后结果就不一样了。

我做错了吗?有什么我想念的吗?我可以清楚地看到方法内部的值是 true,但在调用站点上,它的显示方式不同。

【问题讨论】:

  • 能否提供 Blend() 方法的代码?
  • 也许添加一些更完整的代码。我仍然看不到您如何在静态方法中获得this
  • 我添加了 Blend 的代码,现在就是这样,因为我正在像这样调试它。 Type.GetMethods 和 method.Invoke,它们在 Effect 实例类中,通过反射调用 Blend 方法。
  • 您的变量成功的范围是静态方法,而不是在您的 EffectMethods 类中声明为静态成员,对吗?您是否在静态方法中使用任何 lambda 表达式?
  • @Joel,这是正确的,没有 lambda。它实际上是设置一些值,例如成功并创建一个 EffectResult 实例。

标签: c# .net reflection


【解决方案1】:

我不明白为什么它应该返回“坏值”。你没有提供完整的代码,所以我只能给你我的两个猜测。

  1. EffectResult的构造函数中,忘记给属性设置success参数,或者属性实现错误。

  2. 用于获取方法的 Type 不是 EffectMethods,或者您的 AppDomain 中有具有不同实现的重复程序集。检查加载的模块。

【讨论】:

  • 你在#1 上是对的,只是检查了一下,这是真的。不敢相信我错过了这个。非常感谢您帮助我。
  • 它发生了 :-) 即使是最小的错误也会时不时地折磨我们。
  • 是的,我知道,但是当它发生在我身上时,我讨厌它:O
【解决方案2】:

你能发布更多代码吗?我根据您显示的代码猜测一些定义。使用我猜测的定义我没有问题,当然我假设只有一个公共静态方法和一些基本定义等。

不过,对于这些类或骨架,查看您的实际代码会更有帮助。但是,使用这些,它可以工作。

using System;
using System.Reflection;

public enum EffectType
{
    A,
    B
}

public class Effect
{
    public EffectType Type { get; set; }
}

public class EffectResult
{
    public EffectType Type { get; set; }
    public bool Success { get; set; }

    public EffectResult(EffectType type, bool success)
    {
        Type = type;
        Success = success;
    }
}

public class EffectMethods
{
    public static EffectResult Blend(Effect effect)
    {
        bool success = true;
        return new EffectResult(effect.Type, success);
    }
}

public static class Program
{
    public static void Main()
    {
        var methods = typeof (EffectMethods).GetMethods(BindingFlags.Public | BindingFlags.Static);

        var result = methods[0].Invoke(null, new object[] { new Effect { Type = EffectType.A } });

        Console.WriteLine(result);
    }
}

【讨论】:

    猜你喜欢
    • 2012-08-08
    • 2014-03-02
    • 1970-01-01
    • 2017-11-28
    • 2018-10-30
    • 1970-01-01
    相关资源
    最近更新 更多