将属性传递给方法以更改该属性
不确定这是否可行,但这就是我想要做的:
我想要一个字典,其中包含列索引到用于填充该索引的属性名称的映射。
在我的代码中,我将循环遍历一个数组 if strings 并使用字典来查找它应该映射到哪一列。
我的最终结果代码如下所示:
for(int index = 0; index < fields.Length)
{
fieldPropertyMapping[index] = StripQuotes(fields[index]);
}
Not sure if this is possible, but here is what I am trying to do:
I want to have a dictionary that contains a mapping of a column index to a property name used to populate that index.
In my code I will loop through an array if strings and use the dictionary to look up which column it should map to.
My end result code would look like:
for(int index = 0; index < fields.Length)
{
fieldPropertyMapping[index] = StripQuotes(fields[index]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要执行您具体要求的操作,您必须使用反射(正如您标记问题一样)来执行此操作。看一下
PropertyInfo
类。我不完全确定您的代码在做什么,但反射性设置属性值的一般示例是:但是,如果您知道该属性,您可以改为传递
Action
在代码中的某个时刻。例如:或者,如果您在调用时知道类型但没有实例,则可以将其设为
Action
。这也可以防止创建闭包。要使其完全通用(“通用”如“非特定”中的“通用”,而不是通用中的“通用”),您可能必须将其设为
Action
To do what you're asking specifically, you'll have to use reflection (as you tagged your question) to do this. Have a look at the
PropertyInfo
class. I'm not entirely certain what your code is doing, but a general example of reflectively setting a property value would be:You could, however, pass an
Action<T>
instead, if you know the property at some point in the code. For example:Or, if you know the type when you call it but you don't have the instance, you could make it an
Action<YourType, PropertyType>
. This also would prevent creating a closure.To make this fully generic ("generic" as in "non-specific", not as in generics), you'll probably have to make it an
Action<object>
and cast it to the proper property type within the lambda, but this should work either way.您有几个选择:
PropertyInfo
对象并将其传递到该方法中,并通过反射设置它的值。You have a couple of choices:
PropertyInfo
object into the method and set it's value through reflection.您可以使用反射来获取类的属性:
you can use reflection to get the properties for a class: