【发布时间】:2019-09-02 20:21:04
【问题描述】:
当尝试从派生属性或使用 CanRead / CanWrite 获取属性访问器时,由于某些原因,基本自动属性不会被考虑在内。
CanRead 和 CanWrite 返回值仅基于派生类型,GetMethod 和 SetMethod 也不包含来自基类型的方法。
但是,当从基类型编写代码访问器时,可以使用(这样我们就可以读取覆盖的自动属性,只在派生类型中定义 setter)。
这里是重现它作为单元测试编写的代码:
using System.Reflection;
using NUnit.Framework;
[TestFixture]
public class PropertiesReflectionTests
{
public class WithAutoProperty
{
public virtual object Property { get; set; }
}
public class OverridesOnlySetter : WithAutoProperty
{
public override object Property
{
set => base.Property = value;
}
}
private static readonly PropertyInfo Property = typeof(OverridesOnlySetter).GetProperty(nameof(OverridesOnlySetter.Property));
// This one is passing
[Test]
public void Property_ShouldBeReadable()
{
var overridesOnlySetter = new OverridesOnlySetter {Property = "test"};
Assert.AreEqual(overridesOnlySetter.Property, "test");
}
// This one is failing
[Test]
public void CanRead_ShouldBeTrue()
{
Assert.True(Property.CanRead);
}
// And this is failing too
[Test]
public void GetMethod_ShouldBeNotNull()
{
Assert.NotNull(Property.GetMethod);
}
}
我希望最后两个测试通过,我错过了什么?
【问题讨论】:
-
如果你不指定getter,那么显然
Property.GetMethod会返回null。你期待什么? -
@haim770 该属性已被覆盖,我可以从中读取一个值(因为它在基类中有一个 getter)。但是我不能通过反射得到这个get方法。这就是困扰我的地方。
-
@haim 我更新了示例并包括通过派生类型的对象从该属性读取的通过测试。
标签: c# .net reflection system.reflection