是否可以通过反射设置私有属性?
我可以通过反射设置私有属性吗?
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
:
var t = typeof(Entity);
var mi = t.GetMethod("set_CreatedOn", BindingFlags.Instance | BindingFlags.NonPublic);
我想我可以做到这一点,但我无法解决。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的:
Yes, it is:
编辑:由于属性本身是公共的,因此您显然不需要使用 BindingFlags.NonPublic 来查找它。尽管 setter 的可访问性较低,但调用
SetValue
仍然可以达到您的预期。EDIT: Since the property itself is public, you apparently don't need to use
BindingFlags.NonPublic
to find it. CallingSetValue
despite the the setter having less accessibility still does what you expect.您可以通过代码从派生类型访问私有设置器
You can access private setter from derived type via code
这些都不适合我,而且我的属性名称是唯一的,所以我只使用了这个:
None of these worked for me, and my property name was unique, so I just used this:
使用
定义
}
Use
Definition
}