gpt4 book ai didi

c# - 检查方法是否实现了标有属性的接口(interface)方法

转载 作者:太空狗 更新时间:2023-10-30 00:30:43 27 4
gpt4 key购买 nike

Roslyn 是否有可能确定一个类方法是否实现了一些标有属性的接口(interface)方法?

特别是在 wcf 中,我们使用接口(interface)描述服务契约。它的每个方法都应该用 OperationContractAttribute 标记,如下例所示

[ServiceContract]
public interface ISimleService
{
[OperationContract]
string GetData(int value);
}

public class SimleService : ISimleService
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}

在 Roslyn ISymbol 接口(interface)中为我们提供了 GetAttributes() 方法,但在 SimleService.GetData() 方法上调用它返回 0。在 ISimleService.GetData 上调用() 声明它按预期返回 OperationContractAttribute

所以通常我必须检查类层次结构以找到所有实现的接口(interface),然后遍历层次结构以找到合适的方法。这是一个困难的方法,我想应该有一个更简单的方法。

最佳答案

是的,可以查明方法是否是接口(interface)方法的实现。这是执行此操作的代码:

methodSymbol.ContainingType
.AllInterfaces
.SelectMany(@interface => @interface.GetMembers().OfType<IMethodSymbol>())
.Any(method => methodSymbol.Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(method)));

您可以修改它以实际获取已实现的方法,然后您可以在上面检查属性。

关于c# - 检查方法是否实现了标有属性的接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33922120/

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