How to reference a field by reflection

 ̄綄美尐妖づ 提交于 2019-12-06 09:20:15

That's because you're trying to create a new instance of Button and trying to get the value of its button1 property, which obviously does not exist.

Replace this:

Type t = f.FieldType;
object o = Activator.CreateInstance(t);

f.GetValue(o);

with this:

object o = f.GetValue(control);

You can use a method like this to obtain the value of a field for any object:

public static T GetFieldValue<T>(object obj, string fieldName)
{
    if (obj == null)
        throw new ArgumentNullException("obj");

    var field = obj.GetType().GetField(fieldName, BindingFlags.Public |
                                                  BindingFlags.NonPublic |
                                                  BindingFlags.Instance);

    if (field == null)
        throw new ArgumentException("fieldName", "No such field was found.");

    if (!typeof(T).IsAssignableFrom(field.FieldType))
        throw new InvalidOperationException("Field type and requested type are not compatible.");

    return (T)field.GetValue(obj);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!