0

我需要使用反射来删除父对象内子对象的引用。

public class ParentObject{
    public object ChildObject {get;set;}
}

/* Implementation */ 

ParentObject parentObject = new ParentObject();
object childObject = new Object();

//I set this using reflection (PropertyInfo SetValue operation)
parentObject.ChildObject = childObject ;

... 
//I want to remove the reference to the child object using reflection
RemoveObjectUsingReflection(parentObject, childObject);

Assert.IsNull(parentObject.ChildObject); //returns true

function RemoveObjectUsingReflection(object parentObject, object childObject)
{
   //Appreciate your help here
}
4

1 回答 1

1

假设我正确理解“删除”的含义,只需将其设置为null

var property = parentObject.GetType().GetProperty("ChildObject"); // get the property
property.SetValue(parentObject, null, null);

这确实让我想知道为什么你需要对此进行反思。

于 2012-06-15T23:38:07.997 回答