【问题标题】:Check if method implements interface method marked with attribute检查方法是否实现了标有属性的接口方法
【发布时间】:2023-04-06 02:45:01
【问题描述】:

Roslyn 是否有可能判断一个类方法是否实现了某个带有属性标记的接口方法?

特别是在 wcf 中,我们使用接口来描述服务契约。它的每个方法都应该用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 接口为我们提供了 GetAttributes() 方法,但在 SimleService.GetData() 方法上调用它返回 0。在 ISimleService.GetData() 声明上调用它按预期返回 OperationContractAttribute

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

【问题讨论】:

  • 在 Wcf 服务中,接口需要用属性OperationContract 标记它们的方法。与其搜索接口实现,不如简单地查找所有标有ServiceContract 的接口并找到该接口中的所有方法,然后应用过滤器查看它们是否都标记为OperationContract

标签: c# wcf roslyn


【解决方案1】:

是的,可以确定一个方法是否是接口方法的实现。这是执行此操作的代码:

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

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

【讨论】:

  • 是的,最后我得到了类似的东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多