是否可以在winforms中使用c#动态显示代码片段格式的文本 [英] Is it possible display the text in code snippet format dynamically using c# in winforms

查看:20
本文介绍了是否可以在winforms中使用c#动态显示代码片段格式的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以从xml文件中提取的代码格式显示问题

How to display the question in the code format which is taken from an xml file

<paper>
 <question>public class MyClass { public int x;public int y; public void Method(){ x=10;} }</question>
</paper>

在 form.cs 中

In 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;} }

但我需要这样显示..我该怎么办

But i need to display like this..what should i have to do

public class MyClass
{
  public int x;
  public int y;
  public void Method()
  { 
     x=10;
  }
}

推荐答案

Anusha,

另存为字符串:

string questions = doc.descedants("question");

然后定义一些分隔符:

char[] delim = { '{', '}', ';', ')' };

然后遍历字符串并相应地处理每个分隔符:

Then iterate through the string and handle each delimiter accordingly:

// 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 循环的开头有额外的空格.

You can change the delimStr to have extra spaces in the beginning of the foreach loop if you want the indent to start with extra space.

我修复了缩进问题.

这篇关于是否可以在winforms中使用c#动态显示代码片段格式的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆