gpt4 book ai didi

c# - 接口(interface)接口(interface) : T

转载 作者:太空狗 更新时间:2023-10-30 01:30:49 26 4
gpt4 key购买 nike

假设我有这样的类和接口(interface)结构:

interface IService {}
interface IEmailService : IService
{
Task SendAsync(IMessage message);
}

class EmailService : IEmailService
{
async Task SendAsync(IMessage message)
{
await ...
}
}

interface ICircuitBreaker<TService> : IService where TService : IService
{
TService Service { get; set; }
Task<IResult> PerformAsync(Func<Task<Iresult>> func);
}

class EmailServiceCircuitBreaker : ICircuitBreaker<IEmailService>
{
IEmailService Service { get; set; }

public EmailServiceCircuitBreaker(IEmailService service)
{
Service = service;
}

public async Task<IResult> PerformAsync(Func<Task<Iresult>> func)
{
try
{
func();
}
catch(Exception e){//Handle failure}
}
}

所以现在我想改变EmailServiceCircuitBreaker到:

class EmailServiceCircuitBreaker : ICircuitBreaker<IEmailService>, IEmailService

所以我可以包装 IEmailService 中的每个方法和 Send(...)看起来像:

async Task<IResult> IEmailService.SendAsync(IMessage m)
=> await PerformAsync(async () => await Service.SendAsync(m));

在 Controller 中,我可以将其用作 IEmailService即使这是 ICircuitBreaker<IEmailService>不知道。

但是,如果我的任何同事会实现 ICircuitBreaker<T>我想强制他的类(class)也实现 T

最佳答案

当你不想有新的语言约束时,你可以在编译时抛出自定义错误

您可以如下创建代码分析,使用 DiagnosticAnalyzer

https://johnkoerner.com/csharp/creating-your-first-code-analyzer/

使用 DiagnosticAnalyzer,您可以搜索模式并抛出异常

 context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType);

private static void AnalyzeSymbol(SyntaxNodeAnalysisContext context)
{
var node = (ObjectCreationExpressionSyntax)context.Node;

if (node != null && node.Type != null && node.Type is IdentifierNameSyntax)
{
var type = (IdentifierNameSyntax)node.Type;

var symbol = (INamedTypeSymbol)context.SemanticModel.GetSymbolInfo(type).Symbol;
var isIService = IsInheritedFromIService(symbol);

if (isIService )
{
... //Check you logic
context.ReportDiagnostic(diagnostic);
}
}
}

private static bool IsInheritedFromIService(ITypeSymbol symbol)
{
bool isIService = false;
var lastParent = symbol;

if (lastParent != null)
{
while (lastParent.BaseType != null)
{
if (lastParent.BaseType.Name == "IService")
{
isIService = true;
lastParent = lastParent.BaseType;
break;
}
else
{
lastParent = lastParent.BaseType;
}
}
}

return isIService ;
}

关于c# - 接口(interface)接口(interface) <T> : T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42900999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com