Reputation: 11
Here I am posting a bit of code which have problem in use of reflection .In button Click I use a messagebox to show my needs. How can I get Name Value without using property.i like to use reflection. [I am able to get it using property]. Here I am getting an error “Non-static method requires a target.” Please help me to correct this code.thanks in advance
public class CustomProperty<T>
{
private T _value;
public CustomProperty(T val)
{
_value = val;
}
public T Value
{
get { return this._value; }
set { this._value = value; }
}
}
public class CustomPropertyAccess
{
public CustomProperty<string> Name = new CustomProperty<string>("cfgf");
public CustomProperty<int> Age = new CustomProperty<int>(0);
public CustomPropertyAccess() { }
}
private void button1_Click(object sender, EventArgs e)
{
CustomPropertyAccess CPA = new CustomPropertyAccess();
CPA.Name.Value = "lino";
CPA.Age.Value = 25;
MessageBox.Show(CPA.GetType().GetField("Name").FieldType.GetProperty("Value").GetValue(null , null).ToString());
}
Upvotes: 0
Views: 852
Reputation: 6085
You have to pass the object (CPA) in the GetValue call instead of null:
MessageBox.Show(CPA.GetType().GetField("Name").FieldType.GetProperty("Value").GetValue(CPA ,null).ToString());
Or was it as the second parameter? Don't remember exactly, so you should have a look in the MSDN for the exact signature of Property.GetValue.
Upvotes: 2