C#:Reflection:子类的访问属性

时间:2014-10-09 15:05:15

标签: c# system.reflection

我试图通过反射来访问子类的属性。但这不起作用。如何才能访问子类的所有属性?

这是我尝试通过反射访问子类属性的类。 我尝试了类结构抽象和部分,但两者都不起作用。

public abstract class FakeDbContext
{
    public FakeDbSet<T> Set<T>() where T : class, IObjectState
    {
        foreach (PropertyInfo property in GetType().GetProperties())
        {
            if (property.PropertyType == typeof(FakeDbSet<T>))
                return property.GetValue(this, null) as FakeDbSet<T>;
        }
        throw new Exception("Type collection not found");
    }
}

带参数

的子类
public class MockDbContext : FakeDbContext
{
    private FakeDbSet<Address> Addresses { get; set; }
    private FakeDbSet<EmailAddress> EmailAddresses { get; set; }
    private FakeDbSet<PhoneNumber> PhoneNumbers { get; set; }
    private FakeDbSet<BaseContact> Contacts { get; set; }
    private FakeDbSet<Environment> Environments { get; set; }
    private FakeDbSet<Data.Entities.InformationService> InformationServices { get; set; }
    private FakeDbSet<UserEnvironmentConfiguration> UserEnvironmentConfigurations { get; set; }
    private FakeDbSet<Customer> Customers { get; set; }
    private FakeDbSet<UserEnvironmentConfigurationSet> UserEnvironmentConfigurationSets { get; set; }

    public MockDbContext()
    {
        Addresses = new FakeDbSet<Address>();
        EmailAddresses = new FakeDbSet<EmailAddress>();
        PhoneNumbers = new FakeDbSet<PhoneNumber>();
        Contacts = new FakeDbSet<BaseContact>();
        Environments = new FakeDbSet<Environment>();
        InformationServices = new FakeDbSet<Data.Entities.InformationService>();
        UserEnvironmentConfigurations = new FakeDbSet<UserEnvironmentConfiguration>();
        Customers = new FakeDbSet<Customer>();
        UserEnvironmentConfigurationSets = new FakeDbSet<UserEnvironmentConfigurationSet>();

        InitData();
    }
}

1 个答案:

答案 0 :(得分:2)

要获取私有媒体资源,您需要使用GetProperties的重载来BindingFlags.NonPublic使用BindingFlags作为参数。

foreach (PropertyInfo property in GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))
{
    ...
}