.NET Reflection设置私有属性

Lie*_*oen 19 .net c# reflection

如果您有一个如下定义的属性:

private DateTime modifiedOn;
public DateTime ModifiedOn
{
    get { return modifiedOn; }
}
Run Code Online (Sandbox Code Playgroud)

如何使用Reflection将其设置为某个值?

我试过了两个:

dto.GetType().GetProperty("ModifiedOn").SetValue(dto, modifiedOn, null);
Run Code Online (Sandbox Code Playgroud)

dto.GetType().GetProperty("modifiedOn").SetValue(dto, modifiedOn, null);
Run Code Online (Sandbox Code Playgroud)

但没有任何成功.很抱歉,如果这是一个愚蠢的问题,但这是我第一次使用Reflection with C#.NET.

Mar*_*ell 36

没有制定者; 你需要:

public DateTime ModifiedOn
{
    get { return modifiedOn; }
    private set {modifiedOn = value;}
}
Run Code Online (Sandbox Code Playgroud)

(你可能不得不使用BindingFlags- 我会稍等一下)

没有setter,你必须依赖模式/字段名称(这是脆弱的),或解析IL(非常难).

以下工作正常:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

它也适用于自动实现的属性:

public DateTime ModifiedOn { get; private set; }
Run Code Online (Sandbox Code Playgroud)

(依赖字段名称可能会破坏)

  • 看起来如果整个属性都是私有的,你只需要`BindingFlags`. (4认同)