使用字符串的反射对象访问 [英] Reflected object access using a string
问题描述
我想仅使用字符串访问通用对象.我知道通过反射可以访问通用对象,所以我需要正确解析字符串表达式,提取对象访问令牌,并使用反射执行它们.
I'd like to access to a generic object using only a string. I know that with reflection it is possible to access to generic object, so I need to parse correctly the string expression, extract object accesses tokens, and execute them using reflection.
看起来很简单,但我发现表达式解析有困难,因为正则表达式.
It seems quite easy, but I found difficoulties in the expression parsing because regular expression.
我的最终目标应该是基于对象属性的字符串渲染.一个例子是 DebuggerDisplayAttribute,它允许生成一个字符串通过访问一个对象.我没有发现任何对执行字符串处理有用的东西;所以我开始使用正则表达式手动解析表达式字符串.
My final target should be a string rendering, based on object properties. An example is the DebuggerDisplayAttribute, which allow to produce a string by accessing to an object. I didn't find anything useful for performing the string processing; so I've started to manually parse the expression string using regular expression.
例如下面的表达式就很简单:
For example, the following expression it quite easy:
"MyFixedString = {PropertyName}"
因此,包含在{ ... }"中的标记代表一个对象属性.提取属性名称,使用反射获取值,调用ToString()方法并替换到表达式字符串上以获取结果.
So, the tokens enclosed to "{ ... }" represents an object property. Extract the property name, get the value using reflection, calls the ToString() method and replace it on the expression string to get the result.
但我想执行更复杂的对象访问:
But Id like to perform more complex object access:
"MyFixedString = {Property.Method(\"MyMethodArg.1\", \"MyMethodArg.2\").Field}"
当然,我知道对象访问是用点分隔的(但这并不简单,因为点可能存在于其他元素(即方法参数)中.此外,我需要识别方法、字段/属性、索引属性.
Of course, I understand that object accesses are separated by dots (but this is not simple since the dots could be present in another elements (i.e. method arguments). Additionally, I need to recognize methods, field/properties, indexed properties.
遗憾的是,我缺少正则表达式基础知识(我发誓我会研究它们!).
Sadly, I'm missing regular expression basics (i swear i'll study them!).
所以,我的问题是:是否有一些内置类可以满足我的需求?如果没有,我需要一个正则表达式,将输入字符串拆分为单个字符(在我的情况下是点和逗号),但不要拆分字符用双引号括起来的情况.
So, my question is: is there some built-in class which do what I need? If not, I need a regular expression which split the input string by a single character (in my cases are dots and commas), but don't split in the case the character is enclosed in double quotes.
最后一个例子将被拆分为
The last example would be splitted in
- 财产
- 方法(\"MyMethodArg.1\", \"MyMethodArg.2\")
- 方法
- "MyMethodArg.1\"
- \"MyMethodArg.2\"
推荐答案
也许你应该看看 FormatWith.
这篇关于使用字符串的反射对象访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!