2011-03-29 47 views
1

我有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,但是在方法通过反射返回后,结果是不同的。

我这样做不对吗?有什么我失踪?我可以清楚地看到该方法中的值是真实的,但在呼叫站点上,它显示的方式不同。

+0

你能提供Blend()方法的代码吗? – Adi 2011-03-29 21:17:48

+0

也许添加一些更完整的代码。我仍然没有看到你如何在静态方法中得到'this'。 – 2011-03-29 21:19:21

+0

我添加了Blend的代码,这就是它现在的样子,因为我正在像这样调试它。 Type.GetMethods和method.Invoke,它们在Effect实例类中,通过反射调用Blend方法。 – 2011-03-29 21:21:40

回答

2

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

  1. EffectResult构造函数,你忘了给success参数设置为一个属性或属性的实现是错误的。

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

+0

你说得对#1,只是检查,它是真实的。不能相信我错过了这一点。非常感谢帮助我。 – 2011-03-29 21:38:41

+2

它发生了:-)即使是最小的错误,我们时常咬我们。 – 2011-03-29 21:40:05

+2

是的,我知道,但当它发生在我身上时,它就会讨厌它:O – 2011-03-29 21:44:34

1

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

虽然,对于那些类或骨架,看看您的实际代码会更有帮助。使用这些虽然,它的作品。

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); 
    } 
}