是否可以通过反射设置私有属性? [英] Is it possible to set private property via reflection?

查看:24
本文介绍了是否可以通过反射设置私有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过反射设置私有属性吗?

Can I set a private property via reflection?

public abstract class Entity
{
    private int _id;
    private DateTime? _createdOn;
    public virtual T Id
    {
        get { return _id; }
        private set { ChangePropertyAndNotify(ref _id, value, x => Id); }
    }
    public virtual DateTime? CreatedOn
    {
        get { return _createdOn; }
        private set { ChangePropertyAndNotify(ref _createdOn, value, x => CreatedOn); }
    }
}

我尝试了以下方法但它不起作用,其中 t 代表一种 Entity:

I've tried the following and it does not work, where t represents a type of Entity:

var t = typeof(Entity);
var mi = t.GetMethod("set_CreatedOn", BindingFlags.Instance | BindingFlags.NonPublic);

我想我可以做到,但我做不到.

I guess I can do this but I can't work it out.

推荐答案

t.GetProperty("CreatedOn")
    .SetValue(obj, new DateTime(2009, 10, 14), null);

由于属性本身是公开的,您显然不需要使用 BindingFlags.NonPublic 来找到它.尽管 setter 的可访问性较低,但调用 SetValue 仍然可以满足您的期望.

Since the property itself is public, you apparently don't need to use BindingFlags.NonPublic to find it. Calling SetValue despite the the setter having less accessibility still does what you expect.

这篇关于是否可以通过反射设置私有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆