本文介绍了NET应用程序中拦截DateTime.Now的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个使用当前日期(使用Datetime.Now)来计算特定值的应用程序。

We have an application which uses the current date (using Datetime.Now) to calculate specific values.

我们需要能够在服务器上运行这些计算也基于其他日期。
不幸的是,两个明显的选择是不可行的-

We need to be able to run these calculations on the server based on a different date as well.Unfortunately the two obvious choices are not viable -

a)尽管我们拥有该应用的代码,但由于政治因素以及其他环境也使用该事实服务,将无法更改它并注入特定日期,并且由于服务器上运行的其他应用程序和进程,我们无法更改系统日期。

a) although we have the code for the app, due to politics and the fact that other environments also use the service, will not be able to change it and inject a specific date and

b)

我想知道的是:

是否有可能拦截对框架的调用(Datetime。现在在这种情况下)并返回一个特定值?
这可以来自同一应用程序,也可以来自同一应用程序。不幸的是,我不确定您是否可以通过这种方式真正拦截这些呼叫,甚至无法识别呼叫过程。
我意识到您可以使用某些测试框架来完成此操作,但是无论如何它们都将要求您更改代码库。

would it be possible to intercept calls made to the framework (Datetime.Now in this case) and return a specific value? This can be from either the same application or not. Unfortunately I'm not sure if you can actually intercept these calls in this way, and even then be able to identify the calling process.I realise you could potentially do this with some testing frameworks, but they will require you to change your codebase in any case.

谢谢

推荐答案

如果除了在运行时修补 DateTime.Now 之外别无其他方法,您-可以通过库做到这一点。我显然不建议这样做,但您可以自己决定。

If you absolutely have no other way than to patch DateTime.Now at runtime - you can do this with Harmony library. I obviously won't recommend to do such things, but you can decide for yourself.

首先下载二进制文件(尚无nuget软件包)。然后引用它:

First download binary here (no nuget package yet). Reference it and then:

class Program {
    static void Main(string[] args) {
        var now = DateTime.Now; // normal now
        var harmony = HarmonyInstance.Create("test");
        // patch
        harmony.PatchAll(Assembly.GetExecutingAssembly());
        // now + 100 years
        var newNow = DateTime.Now;
    }

    // we are rewriting method get_Now, which is a getter of property Now
    // of type DateTime
    [HarmonyPatch(typeof(DateTime), "get_Now")]
    class Patch {
        // this method runs after original one
        // __result stores value produced by original
        static DateTime Postfix(DateTime __result) {
            // add 100 years to it
            return __result.AddYears(100);
        }
    }
}

这将更改 DateTime.Now 属性getter会在运行时返回原始值+ 100年。显然,您可以更改它以返回所需的任何值。

That will change DateTime.Now property getter at runtime so that it returns its original value + 100 years. You can obviously change that to return any value you need.

此修补程序不会影响任何其他进程, DateTime.Now 将照常工作。

This patch does not affect any other processes, DateTime.Now will work as usual for them.

这篇关于NET应用程序中拦截DateTime.Now的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 21:50