C# 3.0 使用反射从嵌套类获取值

C# 3.0 使用反射从嵌套类获取值,c#-3.0,C# 3.0,在这里,我发布了一些代码,这些代码在使用反射时有问题。在按钮点击中,我使用一个消息框来显示我的需求。不使用属性如何获取名称值。我喜欢使用反射。[我可以使用属性获取它]。这里我得到一个错误“非静态方法需要一个目标”。请帮助我更正此代码。提前谢谢 public class CustomProperty<T> { private T _value; public CustomProperty(T val) { _value = val; }

在这里,我发布了一些代码,这些代码在使用反射时有问题。在按钮点击中,我使用一个消息框来显示我的需求。不使用属性如何获取名称值。我喜欢使用反射。[我可以使用属性获取它]。这里我得到一个错误“非静态方法需要一个目标”。请帮助我更正此代码。提前谢谢

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());
}
公共类CustomProperty
{
私人T_值;
公共客户财产(T val)
{
_值=val;
}
公共价值
{
获取{返回此值。_值;}
设置{this.\u value=value;}
}
}
公共类CustomPropertyAccess
{
公共CustomProperty名称=新CustomProperty(“cfgf”);
公共CustomProperty年龄=新CustomProperty(0);
公共CustomPropertyAccess(){}
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
CustomPropertyAccess CPA=新的CustomPropertyAccess();
CPA.Name.Value=“lino”;
CPA.Age.Value=25;
Show(CPA.GetType().GetField(“Name”).FieldType.GetProperty(“Value”).GetValue(null,null.ToString());
}

您必须在GetValue调用中传递对象(CPA),而不是null:

MessageBox.Show(CPA.GetType().GetField("Name").FieldType.GetProperty("Value").GetValue(CPA ,null).ToString());
还是作为第二个参数?不记得很清楚,所以您应该在MSDN中查找Property.GetValue的确切签名