【问题标题】:How to use C# reflection to get properties that are instantiated or properties of a class type that are not null如何使用 C# 反射来获取实例化的属性或不为空的类类型的属性
【发布时间】:2019-06-11 03:10:04
【问题描述】:

我是反射新手,我想知道如何过滤掉私有属性并且只获取实例化的属性。下面给出了我想要实现的示例。

public class PersonalDetails
{
    internal Address AddressDetails { get; set; }
    public Contact ContactDetals { get; set; }
    public List<PersonalDetails> Friends { get; set; }
    public string FirstName { get; set; }
    private int TempValue { get; set; }
    private int Id { get; set; }

    public PersonalDetails()
    {
        Id = 1;
        TempValue = 5;
    }
}

public class Address
{
    public string MailingAddress { get; set; }
    public string ResidentialAddress { get; set; }
}

public class Contact
{
    public string CellNumber { get; set; }
    public string OfficePhoneNumber { get; set; }
}

PersonalDetails pd = new PersonalDetails();
pd.FirstName = "First Name";
pd.ContactDetals = new Contact();
pd.ContactDetals.CellNumber = "666 666 666";

当我得到对象 pd 的属性时,我想过滤掉私有且未实例化的属性,例如属性 TempValueId详细地址

提前致谢。

【问题讨论】:

  • TempValue 总是被实例化,它是一个值类型,你的意思是所有没有设置为default 的地方(对于int0) .还有你的反射代码在哪里?
  • 是的,私有属性可以被实例化,但由于它们是私有的,我想避免它们。
  • 我基本上想要非私有和实例化的属性,包括值类型

标签: c# .net reflection .net-core system.reflection


【解决方案1】:

也许是这样

var p = new PersonalDetails();

var properties = p.GetType()
                  .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                  .Where(x => x.GetValue(p) != null && !x.GetMethod.IsPrivate && !x.SetMethod.IsPrivate)
                  .ToList();

其他资源

BindingFlags Enum

指定控制绑定和搜索方式的标志 对于成员和类型是通过反射进行的。

PropertyInfo.GetValue Method

返回指定对象的属性值。

【讨论】:

  • 由于 BindingFlag 是公共的,这是否也会使用内部修饰符来拉取属性?
  • @BipinR 所以你也想要内部?
  • 是的,我基本上是在做 var properties = pd.GetType().GetProperties();但它只是拉公共属性,而不是内部属性,如果我使用 BindingFlag.NonPublic 它也会带来私有属性。
  • @BipinR 小模组,我忘了加SetMethod
猜你喜欢
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 2011-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多