我刚写了以下函数:
public string Ebnf { get { var props = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); var ruleProps = from p in props where p.PropertyType.IsSubclassOf(typeof(ARule)) select p; var rules = from p in ruleProps select (ARule)p.GetValue(this, null); var ebnfs = from r in rules select r.Name + " = " + r.Ebnf + "."; return string.Join("\n", ebnfs.ToArray()); } }
我开始想知道Linq是否真的为我节省了空间,或者我是否只是为了它而使用Linq:
public string EbnfNonLinq { get { var ebnfs = new List(); var props = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var p in props) { if (p.PropertyType.IsSubclassOf(typeof(ARule))) { var r = (ARule)p.GetValue(this, null); ebnfs.Add(r.Name + " = " + r.Ebnf + "."); } } return string.Join("\n", ebnfs.ToArray()); } }
7行代码与5行:这是一个节省.但我想知道第一个功能的密度是否太大.(这不是性能关键代码,所以我并不担心.)
您认为哪个更漂亮,更易于理解,更易于理解?
蓬松的语法很蓬松.Terse语法很简洁.
public string Ebnf { get { var props = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); string[] ebnfs = props .Where(prop => prop.PropertyType.IsSubclassOf(typeof(ARule))) .Select(prop => (ARule)prop.GetValue(this, null)) .Select(rule => rule.Name + " = " + rule.Ebnf + ".") .ToArray(); return string.Join("\n", ebnfs); } }