用CodeDOM编程生成C#代码文档(摘要)
本文关键字:文档 摘要 代码 CodeDOM 编程 | 更新日期: 2023-09-27 18:00:19
我想用CodeDOM生成C#代码文档。
无文档代码:
public class MyType {
public static BitmapImage File {
get { return GetFile("..."); }
}
}
带文档的代码:
/// <summary> Gets the File from the location </summary>
public class MyType {
public static BitmapImage File {
get { return GetFile("..."); }
}
}
或
/// <summary>
/// Gets the File from the location
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public class MyType {
public static BitmapImage File {
get { return GetFile("..."); }
}
}
我可以生成Class,Member,我可以添加一些属性和装饰器,但如何生成文档-不幸的是没有。
我如何生成成员:
private CodeTypeDeclaration CreateType() {
var classType = new CodeTypeDeclaration("MyType") {
Attributes = MemberAttributes.Public | MemberAttributes.Static
};
var properties = CreateMembers();
classType.Members.AddRange(properties);
return classType;
}
private CodeTypeMember[] CreateMembers() {
var members = _members.Where(x => IsMy(x.Name));
var props = members.Select(CreateProperty).ToArray();
return props;
}
private CodeTypeMember CreateProperty(X x) {
var name = Path.GetFileNameWithoutExtension(x.Name);
var property = new CodeMemberProperty {
Name = name,
HasGet = true,
Attributes = MemberAttributes.Public | MemberAttributes.Static,
Type = new CodeTypeReference(typeof(BitmapImage)),
};
var targetObject = new CodeTypeReferenceExpression(typeof(Y));
var method = Return(new CodeMethodInvokeExpression(targetObject, "Getx", Primitive(x.Name)));
property.GetStatements.Add(method);
return property;
}
private bool IsMy(string path) {
var extension = Path.GetExtension(path.ToLower());
var isMy = Regex.IsMatch(extension, @"'.(jpg)$");
return isMy;
}
编辑:
添加实现:
private CodeTypeMember CreateProperty(X x) {
var name = Path.GetFileNameWithoutExtension(x.Name);
var property = new CodeMemberProperty {
Name = name,
HasGet = true,
Attributes = MemberAttributes.Public | MemberAttributes.Static,
Type = new CodeTypeReference(typeof(BitmapImage)),
};
var targetObject = new CodeTypeReferenceExpression(typeof(Y));
var method = Return(new CodeMethodInvokeExpression(targetObject, "Getx", Primitive(x.Name)));
property.GetStatements.Add(method);
//because CodeMemberProperty.Comments is readonly I cast it to CodeTypeMember, which has read/write Comments
var docStart = new CodeCommentStatement("<summary>", true);
var fileSystemName = string.Format("File system Name: {0}", x.Name);
var docContent = new CodeCommentStatement(fileSystemName, true);
var docEnd = new CodeCommentStatement("</summary>", true);
var result = property as CodeTypeMember;
result.Comments.AddRange(new CodeCommentStatementCollection {
docStart,
docContent,
docEnd
});
return result;
}
CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");
class1.Comments.Add(new CodeCommentStatement("<summary>", true));
class1.Comments.Add(new CodeCommentStatement("Create a Hello World application.", true));
class1.Comments.Add(new CodeCommentStatement("</summary>", true));
如何:使用CodeDOM 创建XML文档文件