相关疑难解决方法(0)

是否可以通过反思设置私有财产?

我可以通过反思设置私有财产吗?

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

我已经尝试了以下它并不起作用,其中t代表一种类型Entity:

var t = typeof(Entity);
var mi = t.GetMethod("set_CreatedOn", BindingFlags.Instance | BindingFlags.NonPublic);
Run Code Online (Sandbox Code Playgroud)

我想我可以做到这一点,但我无法解决这个问题.

.net reflection properties private

117
推荐指数
4
解决办法
6万
查看次数

拥有受保护的二传手的Moq财产

我想要Moq下一个对象:

abstract class Foo
{
    public string Bar { get; protected set; }
}
Run Code Online (Sandbox Code Playgroud)

所以new Mock<Foo>().Bar回归"Blah".

我怎样才能做到这一点?


fooMock.SetupGet<string>(s => s.Bar).Returns("Blah");
Run Code Online (Sandbox Code Playgroud)

失败:System.NotSupportedException:非虚拟成员上的设置无效:s => s.Date

fooMock.Protected().SetupGet<string>("Bar").Returns("Blah");
Run Code Online (Sandbox Code Playgroud)

要指定公共属性StatementSection.Date的设置,请使用类型化重载

.net c# unit-testing moq mocking

10
推荐指数
2
解决办法
5660
查看次数

标签 统计

.net ×2

c# ×1

mocking ×1

moq ×1

private ×1

properties ×1

reflection ×1

unit-testing ×1