等价于 .NET Core 2.0 中的 PropertyInfo.IsPublic

Equivalent of PropertyInfo.IsPublic in .NET Core 2.0

我正在尝试获取以下类型的所有 public 属性。 在 .NET Framework 中,我会通过使用 PropertyInfo 类型的 IsPublic 来做到这一点,但在 .NET Core 2 中似乎不存在。

internal class TestViewModel
{
    public string PropertyOne { get; set; }
    public string PropertyTwo { get; set; }
}

//how can I retrieve an IEnumerable with PropertyOne and PropertyTwo ONLY?
var type = typeof(TestViewModel);
var properties = type.GetProperties().Where(p => /*p.IsPublic &&*/ !p.IsSpecialName);

您可以像在 "classical" .NET

中那样使用绑定标志
    //how can I retrieve an IEnumerable with PropertyOne and PropertyTwo ONLY?
    var type = typeof(TestViewModel);
    var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); 

另一种方法是使用 PropertyType 成员,因此..
Programmer().GetType().GetProperties().Where(p => p.PropertyType.IsPublic && p.DeclaringType == typeof(Programmer));

    public class Human
    {
        public int Age { get; set; }
    }

    public class Programmer : Human
    {
        public int YearsExperience { get; set; }
        private string FavLanguage { get; set; }
    }

本次成功returns仅public int YearsExperience。

internal class TestViewModel
{
    public string PropertyOne { get; set; }
    public string PropertyTwo { get; set; }

    private string PrivateProperty { get; set; }
    internal string InternalProperty { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        //how can I retrieve an IEnumerable with PropertyOne and PropertyTwo ONLY?
        var type = typeof(TestViewModel);

        var properties = type.GetProperties();

        foreach (var p in properties)
            //only prints out the public one
            Console.WriteLine(p.Name);
    }
}

您可以指定:

BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance

获取其他类型