0

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());
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.