问题描述
什么是解析在
"(params (abc 1.3)(sdc 2.0)(www 3.05)....)"
进入在形式结构
struct Params
{
double abc,sdc,www....;
}
感谢
Thanks
编辑
的结构始终具有相同的参数(名称相同,仅增加一倍,在编译时知道)..但为了不批..同时..
EDITThe structure always have the same parameters (same names,only doubles, known at compile time).. but the order is not granted.. only one struct at a time..
推荐答案
根据您的完整的语法,你有几个选择:
如果这是一个非常简单的语法,你不必来检验它的错误你可以简单地用下面去(这将是快)
Depending on your complete grammar you have a few options:if it's a very simple grammar and you don't have to test for errors in it you could simply go with the below (which will be fast)
var input = "(params (abc 1.3)(sdc 2.0)(www 3.05)....)";
var tokens = input.Split('(');
var typeName = tokens[0];
//you'll need more than the type name (assembly/namespace) so I'll leave that to you
Type t = getStructFromType(typeName);
var obj = TypeDescriptor.CreateInstance(null, t, null, null);
for(var i = 1;i<tokens.Length;i++)
{
var innerTokens = tokens[i].Trim(' ', ')').Split(' ');
var fieldName = innerTokens[0];
var value = Convert.ToDouble(innerTokens[1]);
var field = t.GetField(fieldName);
field.SetValue(obj, value);
}
这简单的方法却需要一个很好符合的字符串,否则会出现异常。
that simple approach however requires a well conforming string or it will misbehave.
如果语法是有点复杂的如嵌套(),那么简单的办法是行不通的。
If the grammar is a bit more complicated e.g. nested ( ) then that simple approach won't work.
您可以尝试使用正则表达式,但仍需要一个相当简单的语法,所以如果你最终具有复杂语法您最好的选择是一个真正的解析器。 是易于使用的,因为你可以在简单的C#它写(有些BNF的知识虽然加号)。
you could try to use a regEx but that still requires a rather simple grammar so if you end up having a complex grammar your best choice is a real parser. Irony is easy to use since you can write it all in simple c# (some knowledge of BNF is a plus though).
这篇关于在C#字符串解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!