是否可以通过反射来设置私有财产?可以通过、射来、财产

由网友(殇灬鈊誶)分享简介:我可以通过反射设置了私有财产?公共抽象类实体{私人诠释_id;私营的DateTime? _创建于;公众实际的t标识{{返回_id; }私人集合{ChangePropertyAndNotify(REF _id,价值,X => ID); }}公共虚拟日期时间?创建于{{返回_createdOn; }私人集合{Cha...

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

 公共抽象类实体
{
    私人诠释_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.

阅读全文

相关推荐

最新文章