是否有可能在winforms中使用c#动态显示代码片段格式的文本?
本文关键字:片段 代码 格式 文本 动态显示 有可能 winforms 是否 | 更新日期: 2023-09-27 18:18:59
如何以取自xml文件的代码格式显示问题
<paper>
<question>public class MyClass { public int x;public int y; public void Method(){ x=10;} }</question>
</paper>
在form.cs XDocument doc=new XDocument();
doc.load(path of an xml file);
var questions=doc.descedants("question");
foreach( var ques in questions)
{
label.Text=ques.Value;
}
this.Controls.Add(label1);
显示类似
的输出public class MyClass { public int x;public int y; public void Method(){ x=10;} }
但是我需要这样显示,我该怎么做
public class MyClass
{
public int x;
public int y;
public void Method()
{
x=10;
}
}
Anusha,
保存为字符串:
string questions = doc.descedants("question");
然后定义一些分隔符:
char[] delim = { '{', '}', ';', ')' };
然后遍历字符串并相应地处理每个分隔符:
// You don't have to use StringBuilder, but it makes it easier to read.
StringBuilder sb = new StringBuilder();
// Iterate through and handle each character in string.
int indentAmt = 0;
string indentStr = string.Empty;
foreach (char c in questions)
{
// Determine the indent of the current line.
indentStr = string.Empty;
for (int i = 0; i < indentAmt; i++)
indentStr += " ";
// Update the indent amount.
if (c == '{')
indentAmt++;
else if (c == '}')
indentAmt--;
// Add a new line, plus the character, if the character is one of the delimiters.
if (delimiters.Contains(c))
sb.Append(c.ToString() + Environment.NewLine + indentStr);
else
sb.Append(c);
}
questions = sb.ToString(); // BOOM.
如果您希望缩进以额外的空格开始,可以将delimStr更改为在foreach循环的开头有额外的空格。
编辑:我修复了缩进问题。