English 中文(简体)
利用反射从nes类中获取价值
原标题:Get value from nested class using reflection
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() { }
}

//I jest beginer in reflection. 

//How can access GetValue of  CPA.Age.Value using fuly reflection


private void button1_Click(object sender, EventArgs e)
{
   CustomPropertyAccess CPA = new CustomPropertyAccess();
   CPA.Name.Value = "lino";
   CPA.Age.Value = 25;

//I did like this . this is the error   “ Non-static method requires a target.”
MessageBox.Show(CPA.GetType().GetField("Name").FieldType.GetProperty("Value").GetValue(null     ,null).ToString());

}
问题回答

如何使用这种方法:

public Object GetPropValue(String name, Object obj) {
    foreach (String part in name.Split( . )) {
        if (obj == null) { return null; }

        Type type = obj.GetType();
        PropertyInfo info = type.GetProperty(part);
        if (info == null) { return null; }

        obj = info.GetValue(obj, null);
    }
    return obj;
}

并如此:

Object val = GetPropValue("Age.Value", CPA);

阅读错误信息。

非统计方法和财产与某类人员有关,因此,在试图通过思考获得这些人员时,你需要提供实例。

在<代码>GetProperty中。 GetValue方法,你需要具体说明你想要获得财产价值的物体。 您的情况是:





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签