簡體   English   中英

使用反射調用靜態方法時得到錯誤的返回值?

[英]Getting wrong return values when using reflection to call a static method?

我有兩種類型,分別稱為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,但是在方法通過反射返回后,結果將有所不同。

我做錯了嗎? 我有什么想念的嗎? 我可以清楚地看到該方法內部的值是正確的,但是在調用站點上,它的顯示方式有所不同。

我不明白為什么它應該返回“不良價值”。 您沒有提供完整的代碼,所以我只能給我兩個猜測。

  1. EffectResult的構造函數中,您忘記了將success參數設置為一個屬性,否則該屬性的實現是錯誤的。

  2. 用於獲取方法的Type不是EffectMethods或者您的AppDomain中具有重復的程序集,它們具有不同的實現。 檢查已加載的模塊。

你能發布更多代碼嗎? 我正在根據您顯示的代碼猜測一些定義。 使用我猜測的定義,我沒有問題,當然,我假設只有一種公共靜態方法和一些基本定義,等等。

不過,對於那些類或框架,查看實際代碼會更有用。 盡管使用這些,它仍然有效。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM