【问题标题】:Create Method/Answer Method from caller从调用者创建方法/应答方法
【发布时间】:2013-06-12 21:05:37
【问题描述】:

我有一个很奇怪的问题要做。由于反思,我将一个类指向我的模拟类而不是“真实”类。 (测试目的)。我想知道是否有任何方法可以在模拟中捕获任何方法调用,并根据调用正在等待的内容返回我想要的任何内容。

某种意义上的:

一个对象调用另一个对象来执行 X() 并期望一个布尔值。

由于我已经通过反射改变了它指向的对象,我希望我的模拟在调用 X() 时返回“true”(尽管它本身没有实现 X())。

换句话说,不是触发“MethodNotFoundException”,而是接收所有内容并相应地执行一些逻辑。

【问题讨论】:

  • 您可以研究像 Ninject 这样的依赖注入 (DI) 框架来解决此类问题。
  • 你不能为 MethodNotFoundException 做一个捕获吗?您希望它在某些情况下会发生,您可以在其中包含您的自定义逻辑。
  • 我认为您在这里的语言有误...
  • (你可以也许System.Dynamic做点什么,但这既不简单也不直接。)
  • @millimoose Method_missing 从那个链接真的很有帮助。只需在 Google 中搜索 C# 版本,我就知道了:)

标签: c#


【解决方案1】:

感谢@millimoose,最好的方法(而且非常简单)是:

DynamicObject.TryInvoke 方法

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvoke.aspx

再次感谢!

【讨论】:

    【解决方案2】:

    您得到的异常可能是MissingMethodException。 也许下面的控制台应用程序可以引导您实现更具体的实现,但逻辑应该是相同的:

    class Program
    {
        /// <summary>
        /// a dictionary for holding the desired return values
        /// </summary>
        static Dictionary<string, object> _testReturnValues = new Dictionary<string, object>();
    
        static void Main(string[] args)
        {
            // adding the test return for method X
            _testReturnValues.Add("X", true);
    
            var result = ExecuteMethod(typeof(MyClass), "X");
            Console.WriteLine(result);
        }
    
        static object ExecuteMethod(Type type, string methodName)
        {
            try
            {
                return type.InvokeMember(methodName, BindingFlags.InvokeMethod, null, null, null);
            }
            catch (MissingMethodException e)
            {
                // getting the test value if the method is missing
                return _testReturnValues[methodName];
            }
        }
    }
    
    class MyClass
    {
        //public static string X() 
        //{
        //    return "Sample return";
        //}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多