相关疑难解决方法(0)

有没有办法使用反射在struct实例上设置属性?

我正在尝试编写一些在结构上设置属性的代码(重要的是它是结构上的属性)并且它失败了:

System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle();
PropertyInfo propertyInfo = typeof(System.Drawing.Rectangle).GetProperty("Height");
propertyInfo.SetValue(rectangle, 5, null);
Run Code Online (Sandbox Code Playgroud)

高度值(由调试器报告)永远不会设置为任何值 - 它保持默认值0.

我之前已经对课程进行了大量的反思,但这种方法运行良好.另外,我知道在处理结构时,如果设置字段,则需要使用FieldInfo.SetValueDirect,但我不知道PropertyInfo的等效项.

c# reflection propertyinfo

48
推荐指数
2
解决办法
9837
查看次数

使用autofixture创建结构不会引发公共构造函数错误

我有一个结构,例如:

public struct Foo
{
    public int Bar;
    public string Baz;
}
Run Code Online (Sandbox Code Playgroud)

并希望使用自动混合在我的单元测试中创建它.我尝试使用以下内容:

IFixture fixture = new Fixture();
var f = fixture.CreateAnonymous<Foo>();
Run Code Online (Sandbox Code Playgroud)

但这会引发AutoFixture was unable to create an instance错误.是否可以使用自动混合自动创建结构?怎么可以这样做?请注意,我正在处理遗留代码,因此需要处理结构.:)

编辑:

IFixture fixture = new Fixture().Customize(new AutoMoqCustomization());
Run Code Online (Sandbox Code Playgroud)

IFixture fixture = new Fixture();
Run Code Online (Sandbox Code Playgroud)

因为它与这个问题无关.

c# unit-testing autofixture

8
推荐指数
1
解决办法
932
查看次数

标签 统计

c# ×2

autofixture ×1

propertyinfo ×1

reflection ×1

unit-testing ×1