简体   繁体   English

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

[英]Equivalent of PropertyInfo.IsPublic in .NET Core 2.0

I'm trying to get all public properties in the below type. 我正在尝试获取以下类型的所有公共属性。 In .NET Framework I'd to that by using IsPublic from the PropertyInfo type but that does not seem to exist in .NET Core 2. 在.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);

You could use binding flags as in "classical" .NET 你可以在“经典”.NET中使用绑定标志

    //how can I retrieve an IEnumerable with PropertyOne and PropertyTwo ONLY?
    var type = typeof(TestViewModel);
    var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); 

An alternative is to use the PropertyType member, as such.. 另一种方法是使用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; }
    }

This successfully returns only the public int YearsExperience. 这成功地仅返回公共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);
    }
}

You can specify: 您可以指定:

BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance

to get other types 得到其他类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM