获取 XML 文档评论

Get XML Documentation Comments

/// <summary>  
///  This can have any description of the class  
/// </summary>  
public class MyClass {} 

在上面的代码示例中,有什么方法可以获得 summary 值。

我的 objective 是在日志中记录对象的操作,在这种情况下,我知道 class 做了什么,什么时候做了什么。

我可以从 this.GetType().Name 中获取 class 的名称,但在某些情况下,我将需要与之关联的任何描述。

如果除了 XML 文档之外,还有其他方法可以描述 class,那么我想听听。

谢谢,

您无法从反射中获取 XML 文档,因为它没有生成到程序集中。它会生成一个单独的 XML 文件,您可以打开该文件并从您的应用程序中读取。 (分发可能是个问题,因为 XML 文件是在程序集编译后生成的,所以您不能将它作为资源包含在程序集本身中。)

另一种解决方案可能是创建一个特殊属性,which you can fill and read。类似于:

[Summary("This can have any description of the class.")]
public class MyClass {}

该解决方案的问题在于它不会生成文档 XML,因此您没有 IntelliSense 等

如果您不想使用 XML 评论,您可以使用 [Description] 属性将描述存储为元数据,即:

[Description("This can have any description of the class")]
public class MyClass {} 

然后您可以在 运行 时访问此属性的值:

public static string GetDescription(Type t) {
    return TypeDescriptor.GetAttributes(t)
        .OfType<DescriptionAttribute>()
        .Select(x => x.Description)
        .FirstOrDefault();
}

例如GetDescription(typeof(MyClass))