使用程序集从DLL文件获取操作契约



我使用Assembly类打开DLL文件。现在我想要获得具有[OperationContract]属性的方法。怎么做呢?

Assembly assembly = Assembly.LoadFrom(someDLLFilePath);
Type[] classes = assembly.GetTypes();
var foo = from type in assembly.GetTypes()
          where type.GetCustomAttributes(false).OfType<ServiceContractAttribute>().Any()
          from method in type.GetMethods()
          where method.GetCustomAttributes(false).OfType<OperationContractAttribute>().Any()
          select method;

没有一条指令可以做到这一点,您必须迭代方法并查看它是否具有该属性。你可以这样写:

foreach (var type in classes)
{
  type.GetMethods().Where(m => m.GetCustomAttributes(false).Contains(typeof (OperationContract)));
}

试试这个:

var result = assembly
    .DefinedTypes
    .SelectMany(type => type.GetMethods()
                            .Where(method => method
                                .GetCustomAttributes<OperationContractAttribute>()
                                .Count() > 0)
        );

最新更新