I have 2 types called Effect
and EffectMethods
which is the static class I am calling the method of:
public class EffectMethods
{
public static EffectResult Blend (Effect effect)
{
bool success = true;
return new EffectResult ( effect.Type, success );
}
}
I find the right method using:
Type.GetMethods ( BindingFlags.Public | BindingFlags.Static );
and filter out the right one.
But when I call it:
( 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 } );
}
}
I am getting the wrong result. Here this
is the current instance of Effect
because it's the type that includes the reflection call.
Basically one of the values I calculate is a flag that returns whether the operation is successful. But this value is set to true in code, but after the method returns via reflection the result is different.
Am I doing this wrong? Is there something I am missing? I can clearly see the value to be true inside the method but on the call site, it shows up differently.
I don't see why it should return "bad value". You didn't provide complete code, so I can only give you my two guesses.
In the constructor of EffectResult
, you forgot to set the success
parameter to a property, or the property implementation is wrong.
The Type
you use to get the methods from is other than EffectMethods
or you have duplicate assemblies with different implementations in your AppDomain. Check the loaded Modules.
Can you post more code? I'm guessing on some of the definitions based on the code you're showing. Using my guessed definitions I have no problems, of course I'm assuming there's only one public static method and some basic definitions, etc.
Would be more helpful to see your actual code, though, for those classes or a skeleton. Using these though, it works.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.