NET反射设置私有财产 [英] .NET Reflection set private property
本文介绍了NET反射设置私有财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果您有这样的定义的属性:
If you have a property defined like this:
private DateTime modifiedOn;
public DateTime ModifiedOn
{
get { return modifiedOn; }
}
你怎么把它设置为某个值与思考?
How do you set it to a certain value with Reflection?
我都试过:
dto.GetType().GetProperty("ModifiedOn").SetValue(dto, modifiedOn, null);
和
dto.GetType().GetProperty("modifiedOn").SetValue(dto, modifiedOn, null);
但没有成功。很抱歉,如果这是一个愚蠢的问题,但它是我第一次使用反射用C#.NET。
but without any success. Sorry if this is a stupid question but it's the first time I'm using Reflection with C#.NET.
推荐答案
这是有否者;你需要:
public DateTime ModifiedOn
{
get { return modifiedOn; }
private set {modifiedOn = value;}
}
(您可能需要使用的BindingFlags
- 我会尝试在某一时刻)
(you might have to use BindingFlags
- I'll try in a moment)
如果没有一个二传手,你必须依靠模式/字段名(这是易碎),或分析IL(很难)。
Without a setter, you'd have to rely on patterns / field names (which is brittle), or parse the IL (very hard).
以下工作正常:
using System;
class Test {
private DateTime modifiedOn;
public DateTime ModifiedOn {
get { return modifiedOn; }
private set { modifiedOn = value; }
}
}
static class Program {
static void Main() {
Test p = new Test();
typeof(Test).GetProperty("ModifiedOn").SetValue(
p, DateTime.Today, null);
Console.WriteLine(p.ModifiedOn);
}
}
这也适用于一个自动实现的属性:
It also works with an auto-implemented property:
public DateTime ModifiedOn { get; private set; }
(其中依靠字段名会破坏可怕的)
(where relying on the field-name would break horribly)
这篇关于NET反射设置私有财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文