首页 > 解决方案 > 在c#中覆盖对象的默认返回

问题描述

在返回对象时,我想确保在返回 if 之前执行操作。有没有办法覆盖对象的默认返回来执行该操作?

例如

//In the constructor I set a query start time
var items = new ListReturnDTO<Product>();

    ....

//I want to set a query end time, but without the need to set the variable in code as it could be forgotten. 
return items;

编辑:

      //I set the QueryStartTime in the constructor
      var items = new ListReturnDTO<Product>();

            items.TotalItem = 11;

            ........

            items.data.Add(new Product { SKU = "000006", Description = "this is the test product 7, a rare breed of product", Price = 65.00, QuantityLeft = 3, Title = "Test Product 7", IsPreview = false });
            items.data.Add(new Product { SKU = "000007", Description = "this is the test product 8, a rare breed of product", Price = 7.00, QuantityLeft = 30, Title = "Test Product 8", IsPreview = false });

            //force a delay to replicate talking to external source
            Thread.Sleep(2000);

            //Currently i set QueryEndTime Here
            items.QueryEndTime = DateTime.UtcNow.TimeOfDay;

            //But i want it to be done automatically on the return (like how I can set QueryStartTime in the constructor, is there an equivalent/an override for the return)
            return Task.FromResult(items);

标签: c#.netasp.net-core.net-core

解决方案


根据我对问题的理解

在方法结束时自动调用一些代码。或者更具体地说,如果方法的返回类型不是 void,则执行一些操作。因此,在给定的示例中,它应该更新 QueryEndTime。

这个概念似乎是面向方面的编程。您可能想尝试的库之一可能是Postsharp。其他人也很少。

Postsharp 有方法装饰器,可以在方法执行前后注入行为。来自上一个链接的示例代码

[PSerializable]
public class LoggingAspect : OnMethodBoundaryAspect
{

  public override void OnEntry(MethodExecutionArgs args)
  {
     Console.WriteLine("The {0} method has been entered.", args.Method.Name);
  }

  public override void OnSuccess(MethodExecutionArgs args)
  {
      Console.WriteLine("The {0} method executed successfully.", args.Method.Name);
  }

  public override void OnExit(MethodExecutionArgs args)
  {
     Console.WriteLine("The {0} method has exited.", args.Method.Name);
  }     

  public override void OnException(MethodExecutionArgs args)
  {
      Console.WriteLine("An exception was thrown in {0}.", args.Method.Name);
  }

}

static class Program
{
   [LoggingAspect]
   static void Main()
   {
     Console.WriteLine("Hello, world.");
   }
}

现在来看您的示例代码,如果是一次看这个答案


推荐阅读