将属性作为要传递和设置的参数传递 [英] Passing properties as parameters to be Got and Set
问题描述
好吧,我需要为许多属性重复相同的代码.
我已经看到了使用Action
代表的示例,但是它们在这里不合适.
Well, I need to repeat same code for many properties.
I've seen examples taking Action
delegates, but they don't fit quite well here.
我想要这样的东西:(请参阅下面的说明)
I want something like this: (see explanation below)
Dictionary<Property, object> PropertyCorrectValues;
public bool CheckValue(Property P) { return P.Value == PropertyCorrectValues[P]; }
public void DoCorrection(Property P) { P.Value = PropertyCorrectValues[P]; }
.
我想拥有一个包含许多属性及其各自正确"值的字典. (我知道它的声明不是很好,但是就是这个主意).属性不必在我的类中,某些属性位于不同程序集的对象中.
I want to have a dictionary containing many properties and their respective "correct" values. (I know it's not well declared, but that's the idea). Properties are not necessarely inside my class, some of them are in objects of different assemblies.
一种方法bool CheckValue(Property)
.此方法必须是属性的access the actual value
和compare to the correct value
.
A method bool CheckValue(Property)
. This method must access the actual value
of the property and compare to the correct value
.
和方法void DoCorrection(Property)
.将此sets the property value
设置为正确的值.
And a method a void DoCorrection(Property)
. This one sets the property value
to the correct value.
请记住,我有很多这些属性,我不想为每个属性手动调用方法.我宁愿在foreach
语句中遍历字典.
Remember I have many of those properties, I wouldn't like to call the methods by hand for each property. I'd rather iterate through the dicionary in a foreach
statement.
所以,主要的问题是标题.
So, the main question is in the title.
-
我已经尝试过
by ref
,但是属性不接受.
我有义务使用reflection
吗???还是有其他选择(如果我需要,也可以接受反射答案).
Am I obligated to use reflection
??? Or is there another option (if I need, reflection answer will be accepted as well).
反正我可以用C#中的pointers
制作字典吗?还是使用changes the value of variable's target
而不是changing the target to another value
的某种分配?
Is there anyway I can make a dictionary with pointers
in C#? Or some kind of assignment that changes the value of variable's target
instead of changing the target to another value
?
感谢您的帮助.
推荐答案
您可以使用反射来做到这一点.使用typeof(Foo).GetProperties()
获取感兴趣对象的属性列表.您的PropertyCorrectValues
属性可以具有类型IDictionary<PropertyInfo, object>
.然后在PropertyInfo
上使用GetValue
和SetValue
方法执行所需的操作:
You can do this using reflection. Get a list of the properties on the object of interest with typeof(Foo).GetProperties()
. Your PropertyCorrectValues
property can have type IDictionary<PropertyInfo, object>
. Then use the GetValue
and SetValue
methods on PropertyInfo
to perform the desired operations:
public bool CheckProperty(object myObjectToBeChecked, PropertyInfo p)
{
return p.GetValue(myObjectToBeChecked, null).Equals(PropertyCorrectValues[p]);
}
public void DoCorrection(object myObjectToBeCorrected, PropertyInfo p)
{
p.SetValue(myObjectToBeCorrected, PropertyCorrectValues[p]);
}
这篇关于将属性作为要传递和设置的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!