C#, .NET 3.5
I am trying to get all of the properties of an object that have BOTH a getter and a setter for the instance. The code I thought should work is
PropertyInfo[] infos = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty);
However, the results include a property that does not have a setter. To give you a simple idea of my inheritance structure that might be affecting this (though I don't know how):
public interface IModel { string Name { get; } } public class BaseModel<TType> : IModel { public virtual string Name { get { return "Foo"; } } public void ReflectionCopyTo(TType target) { PropertyInfo[] infos = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty); foreach (PropertyInfo info in infos) info.SetValue(target, info.GetValue(this, null), null); } } public class Child : BaseModel<Child> { // I do nothing to override the Name property here }
I end up with the following error when working with Name:
System.ArgumentException: Property set method not found.
EDIT: I would like to know why this does not work, as well as what I should be doing to not get the error.
What are Getters and Setters? Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class. Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.
You can only have one getter or setter per name, on an object. (So you can have both one value getter and one value setter, but not two 'value' getters.)
But yes; it is very unusual to have a set-only property. If you expect at least some implementing classes to optionally add a getter, then it makes sense to have it as a setter instead of a SetFoo method. Interfaces don't stand alone, they represent a common subset of the operations on a family of classes.
Call GetGetMethod
and GetSetMethod
on the property - if both results are non-null, you're there :)
(The parameterless versions only return public methods; there's an overload with a boolean parameter to specify whether or not you also want non-public methods.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With