简体   繁体   中英

C# Reflection, how to get property instance within class to setvalue

I'd like to reset the properties of a class back to their default values within a method of the class. My class is instantiated once (is actually a ViewModel in an MVVM framework) and I don't want to destroy and recreate the entire ViewModel, just clear many of the properties. The below code is what I have. The only thing I am missing is how to get the first parameter of the SetValue method - I know it is an instance of the property I am setting, but I cannot seem to figure out how to access that. I get error: "Object does not match target type".

public class myViewModel
{

  ...
  ...

  public void ClearFields()
  {
    Type type = typeof(myViewModel);
    PropertyInfo[] pi = type.GetProperties();
    foreach (var pinfo in pi)
    {
      object[] attributes = pinfo.GetCustomAttributes(typeof(DefaultValueAttribute), false);
      if (attributes.Length > 0)
      {
        DefaultValueAttribute def = attributes[0] as DefaultValueAttribute;
        pinfo.SetValue(?, def.Value, null);
      }
    }

  }

  ...
  ...


}

You should pass an instance of myViewModel , in your case use this to reference the current instance:

public class myViewModel
{

  ...
  ...

  public void ClearFields()
  {
    Type type = typeof(myViewModel);
    PropertyInfo[] pi = type.GetProperties();
    foreach (var pinfo in pi)
    {
      object[] attributes = pinfo.GetCustomAttributes(typeof(DefaultValueAttribute), false);
      if (attributes.Length > 0)
      {
        DefaultValueAttribute def = attributes[0] as DefaultValueAttribute;
        pinfo.SetValue(this, def.Value, null);
      }
    }

  }

  ...
  ...

}

You should put this as a first parameter. See MSDN for reference:

objType: System.Object

The object whose property value will be set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM