c# - 在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);
解决方案
根据我对问题的理解
在方法结束时自动调用一些代码。或者更具体地说,如果方法的返回类型不是 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.");
}
}
现在来看您的示例代码,如果是一次看这个答案。
推荐阅读
- android - 如何修复警告:配置“编译”已过时,已替换为“实施”和“API”
- python - 有没有像 'Exp1 这样的交流电?Exp2 : Python 中的 Exp3'?
- node.js - 代理目标路由到无效 url
- c# - 不同的声音,不同的 imageTargets 和一个按钮。Vuforia (Unity3d)
- php - 从 Synology NAS 连接 mysql
- postgresql - 如何使存档命令从备用到备用 ( scp ) 进行数据库复制。(注意:不是从主人那里待命。)
- wordpress - 即使代码正确,.htaccess 也无法正常工作
- regex - 在记事本++中使用正则表达式覆盖字符串值时需要帮助
- ios - 无法为模拟器构建应用程序:安装了 firebase 插件,但 IOS 中的崩溃运行 BUILD FAILED
- mysql - mysql将星期数转换为星期的日期范围