使用Assembly从DLL文件获取OperationContracts

时间:2013-05-14 09:36:54

标签: c# dll .net-assembly

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

Assembly assembly = Assembly.LoadFrom(someDLLFilePath);
Type[] classes = assembly.GetTypes();

3 个答案:

答案 0 :(得分:2)

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;

答案 1 :(得分:1)

没有一条指令可以执行此操作,您必须迭代方法并查看它是否具有该属性。你可以这样:

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

答案 2 :(得分:1)

试试这个:

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