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

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

问题描述

我可以通过反射设置了私有财产?

 公共抽象类实体
{
    私人诠释_id;

    私营的DateTime? _创建于;

    公众实际的t标识
    {
        {返回_id; }
        私人集合{ChangePropertyAndNotify(REF _id,价值,X => ID); }
    }

    公共虚拟日期时间?创建于
    {
        {返回_createdOn; }
        私人集合{ChangePropertyAndNotify(REF _createdOn,价值,X => CreatedOn); }
    }

}
 

我已经试过以下,它不工作,在那里重新presents一个类型的实体:

  VAR MI = t.GetMethod(set_CreatedOn,BindingFlags.Instance | BindingFlags.NonPublic可);
 

我想我能做到这一点,但我不能工作了。

解决方案

  t.GetProperty(CreatedOn)
    .SetValue(OBJ,新的日期时间(2009年,10,​​14),NULL);
 

编辑:由于物业本身是公共的,你显然并不需要使用 BindingFlags.NonPublic可找到它。呼叫的SetValue 尽管二传手具有较少辅助仍然没有你所期望的。

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

}

I've tried the following and it does not work, where represents a type of 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);

EDIT: 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天全站免登陆