0

好吧,我需要为许多属性重复相同的代码。我已经看到了Action代表的例子,但它们在这里不太适合。

我想要这样的东西:(见下面的解释)

Dictionary<Property, object> PropertyCorrectValues;
public bool CheckValue(Property P) { return P.Value == PropertyCorrectValues[P]; }
public void DoCorrection(Property P) { P.Value = PropertyCorrectValues[P]; }    

.

我想要一个包含许多属性及其各自“正确”值的字典。(我知道它没有很好地声明,但这就是想法)。属性不一定在我的类中,其中一些在不同程序集的对象中。

一种方法bool CheckValue(Property)。这个方法必须access the actual value的属性和compare to the correct value

和一个方法 a void DoCorrection(Property)。这一个sets the property value到正确的值。

请记住,我有许多这些属性,我不想为每个属性手动调用方法。我宁愿在foreach声明中遍历字典。


因此,主要问题在标题中。

  • 我试过了by ref,但属性不接受。

  • 我有义务使用reflection???或者是否有其他选择(如果我需要,也将接受反射答案)。

  • 无论如何我可以用pointersC# 制作字典吗?或者某种类型的任务,changes the value of variable's target而不是changing the target to another value

谢谢您的帮助。

4

2 回答 2

2

您可以使用反射来做到这一点。使用 获取感兴趣对象的属性列表typeof(Foo).GetProperties()。您的PropertyCorrectValues属性可以有 type IDictionary<PropertyInfo, object>。然后使用GetValueandSetValue方法PropertyInfo执行所需的操作:

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]); 
}
于 2013-05-08T22:08:45.497 回答
0

除了 Ben 的代码之外,我还想贡献以下代码片段:

Dictionary<string,object> PropertyCorrectValues = new Dictionary<string,object>();

PropertyCorrectValues["UserName"] = "Pete"; // propertyName
PropertyCorrectValues["SomeClass.AccountData"] = "XYZ"; // className.propertyName

public void CheckAndCorrectProperties(object obj) {
    if (obj == null) { return; }
    // find all properties for given object that need to be checked
    var checkableProps = from props 
            in obj.GetType().GetProperties()
            from corr in PropertyCorrectValues
            where (corr.Key.Contains(".") == false && props.Name == corr.Key) // propertyName
               || (corr.Key.Contains(".") == true && corr.Key.StartsWith(props.DeclaringType.Name + ".") && corr.Key.EndsWith("." + props.Name)) // className.propertyName
            select new { Property = props, Key = corr.Key };
    foreach (var pInfo in checkableProps) {
        object propValue = pInfo.Property.GetValue(obj, null);
        object expectedValue = PropertyCorrectValues[pInfo.Key];
        // checking for equal value
        if (((propValue == null) && (expectedValue != null)) || (propValue.Equals(expectedValue) == false)) {
            // setting value
            pInfo.Property.SetValue(obj, expectedValue, null);
        }
    }
}

使用此“自动”值校正时,您还可以考虑:

  • 您不能PropertyInfo仅通过知道属性名称并且独立于声明类来创建对象;这就是我选择string钥匙的原因。
  • 在不同的类中使用相同的属性名称时,您可能需要更改执行实际赋值的代码,因为正确值和属性类型之间的类型可能不同。
  • 在不同的类中使用相同的属性名称将始终执行相同的检查(请参见上面的点),因此您可能需要属性名称的语法以将其限制为特定的类(简单的点表示法,不适用于命名空间或内部类, 但可能会扩展到这样做)
  • 如果需要,您可以用单独的方法调用替换“检查”和“分配”部分,但它可以在代码块内完成,如我的示例代码中所述。
于 2013-05-08T23:02:04.420 回答