我会使用扩展方法。然后你可以调用 string.bold()。
我认为这是语法:
class xyz {
private string start_bold = "[B]";
private string end_bold = "[/B]";
public static string bold(this string x) {
return start_bold + x + end_bold;
}
}
见:http://msdn.microsoft.com/en-us/library/bb383977.aspx
我将下面的代码作为示例,但我认为您真正需要的是类似于“令牌系统”的东西
假设你有一个这样的字符串:
string s = "I want {~b}this text to be bold{~~b} and {~i}this text to be italics{~~i}"
您的 XML 文档应该包含这些节点(我认为,我的 xml 有点生锈)
<site>
<html>
<style value="{~b}">[b]</style>
<style value="{~~b}">[/b]</style>
<style value="{~i}">[i]</style>
<style value="{~~i}">[/i]</style>
</html>
<phpBBCode>
......
public class Layout {
//private string start_bold = "[B]";
//private string end_bold = "[/B]";
//private string start_italics = "[I]";
//private string end_italics = "[/I]";
private string _stringtoformat;
public string StringToFormat {set{ _stringtoformat = value;}};//syntax is wrong
private string _formattedString;
public string FormattedString {get return _formattedString;}
public Layout(string formattype, int siteid)
{
//get format type logic here
//if(formattype.ToLower() =="html")
//{ . . . do something . . . }
//call XML Doc for specific site, based upon formattype
if(!String.IsNullorEmpty(_stringtoformat))
{
//you will want to put another loop here to loop over all of the custom styles
foreach(node n in siteNode)
{
_stringtoformat.Replace(n.value, n.text);
}
}
//Sorry, can't write XML document parsing code off the top of my head
_formattedString = _stringtoformat;
}
public string bold(this string x) {
return start_bold + x + end_bold;
}
public string italics(this string x) {
return start_italics + x+ end_italics;
}
}
实施
Layout l = new Layout("html", siteidorsomeuniqeidentifier);
l.html = stringtoformat;
output = l.formattedstring;
代码可以更好,但它应该让你朝着正确的方向前进 :)
编辑 2:基于进一步的信息.....
如果你想这样做:
Layout l = new Layout("html");
string s = String.Format("Output of {0} with number {1},
l.bold(Data.Type),
l.italic(Data.Number);
并且您希望根据博客引擎的特定标记更改l.bold() 和l.italic()。 . .
public class Layout {
private string start_bold = "[B]";
private string end_bold = "[/B]";
private string start_italics = "[I]";
private string end_italics = "[/I]";
public Layout(string formattype, int siteid)
{
//get format type logic here
//if(formattype.ToLower() =="html")
//{ . . . do something . . . }
//call XML Doc for specific site, based upon formattype
start_bold = Value.From.XML["bold_start"];
end_bold = Value.From.XML["bold_end"];
//Sorry, can't write XML document parsing code off the top of my head
}
public string bold(this string x) {
return start_bold + x + end_bold;
}
public string italics(this string x) {
return start_italics + x+ end_italics;
}
}
Layout l = new Layout("html", siteid);
string s = String.Format("Output of {0} with number {1},
ValueToBeBoldAsAstring.bold(),
ValueToBeItalicAsAstring.italic());