NET反射设置私有财产反射、财产、NET

由网友(零星的变得优秀,也能拼凑出星河。今日小编为您分享一些冷门却高)分享简介:如果您有这样的定义的属性:If you have a property defined like this:private DateTime modifiedOn;public DateTime ModifiedOn{get { return modifiedOn; }}你怎么把它设置为某个值与思考?How...

如果您有这样的定义的属性:

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)

阅读全文

相关推荐

最新文章