如何在动态类型上执行字符串路径?
是否可以在动态类型上执行字符串路径?
例如,我们可以写动态类型
dynamic d = myObj; var v = d.MyMethod(1,"text").SomeProperty.Name
现在想象我有字符串路径
string path = "MyMethod(1,\"text\").SomeProperty.Name"; var v = d. //How to applay string path to this type?
我有使用扩展方法和reflection的解决方案,您需要优化和测试不同的场景。
编辑仍然是脏代码,但现在支持重载方法。 我将尝试清理代码并使用正则表达式来获得有效和清洁的解决方案
您现在可以为eval方法指定参数的数据类型。
string epath = "GetName(System_String: ding dong, System_Int32:1).name"; MyClass cls = new MyClass(); var v = cls.Eval(epath);
请注意类型名称中的下划线。 如果方法没有重载,这应该不用提及数据类型。 当前限制,你不能在字符串参数值中使用冒号或逗号。 🙁
调用var v = d.Execute(path)
public static object Eval(this object instance, string path) { string[] cmd = path.Split('.'); string subString = cmd[0]; object returnValue = null; Type t = instance.GetType(); if (subString.Contains("(")) { string[] paramString = subString.Split('('); string[] parameters = paramString[1].Replace(")", "").Split(new Char[]{','},StringSplitOptions.RemoveEmptyEntries); bool hasNoParams = parameters.Length == 0; List typeArray = null; if (hasNoParams) typeArray = new List (); foreach (string parameter in parameters) { if (parameter.Contains(":")) { if (typeArray == null) typeArray = new List (); string[] typeValue = parameter.Split(':'); Type paramType = Type.GetType(typeValue[0].Replace('_','.')); typeArray.Add(paramType); } } MethodInfo info = null; if (typeArray == null) info = t.GetMethod(paramString[0]); else info = t.GetMethod(paramString[0], typeArray.ToArray()); ParameterInfo[] pInfo = info.GetParameters(); List
不确定这是否可以轻松实现。 我过去一直在使用Spring.NET Expressions 。
看起来你需要一个eval函数而C#没有,但是如果这个第三方C#eval实现可以处理dynamic
它可能会解决你的问题。