我正在尝试将字符串的一部分转换为不同的对象并将它们加入到列表或数组中,这并不重要。这是一个例子:
示例字符串“这是一个测试字符串。\n \t 这是一个带有制表符的新行”。
我想得到一个输出如下:
new List<OpenXmlElement>(){
new Text("This is a test string."),
new Break(),//this is for the \n char
new TabChar(), //this is for the \t char
new Text("This is a new line with a tab")
};
我已经在字典中有一些字符和类类型,我计划使用反射来实例化它们。
public static Dictionary<string, Type> Tags = new Dictionary<string, Type>()
{
{"\n", typeof(Break)},
{"\t", typeof(TabChar)}
};
我想我可以使用子字符串或正则表达式,但我希望找到一个更清洁的解决方案。
对不起,如果问题不够清楚。我很乐意回答您的任何问题
这是我的全班
public class FormatConverter:IFormatConverter
{
public static Dictionary<string, Type> Tags = new Dictionary<string, Type>()
{
{"\n", typeof(Break)},
{"\t", typeof(TabChar)}
};
public IEnumerable<OpenXmlElement> Convert(string format)
{
foreach (KeyValuePair<string,Type> pair in Tags)
{
var items = format.Split(
new []{pair.Key},StringSplitOptions.RemoveEmptyEntries
);
foreach (var item in items)
{
yield return new Text(item);
yield return Activator.CreateInstance(pair.Value) as OpenXmlElement;
}
format = format.Replace(pair.Key,"");
}
}
}
我知道它有什么问题,只是不知道如何解决它。