2017-09-16 134 views
1

我试图在下面的类型中获取所有公共属性。 在.NET框架我倒是要通过使用IsPublicPropertyInfo类型,但似乎并不在.NET的核心存在2.NET Core 2.0中的PropertyInfo.IsPublic的等价物

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); 
+0

@mjwills不是重复,因为有这么回答建议TypeExtensions,不与.NET核2.0(apparantly)工作。 – NullBy7e

+0

@mjwills我在这里犯了错,我编辑了这个问题并使其更加清晰。 – NullBy7e

回答

1

一种替代方法是使用属性类型构件,因为这种..
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; } 
    } 

这只能成功返回公共int YearsExperience。

+0

这似乎并不奏效,它会从所有继承类型中返回每个公共属性。 – NullBy7e

+0

@NullBy7e更新了答案。 –

+0

谢谢,这似乎工作!虽然下面的答案也适用,但我会将你的答案标记为答案,因为你的声誉较低。 – NullBy7e

2

您可以使用绑定标志为“经典” .NET

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

似乎无效,只有'BindingFlags.Public'枚举为空,并且它包含每个公共属性,包括两个标志时都继承的属性。 – NullBy7e

+0

此方法按预期工作。如果你只想得到在'TestViewModel'(不是继承)中声明的propereties,你应该使用'var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);' –

+0

我把上面的答案标记为解决方案,你的工作,但他有较低的声誉,是吗?否则,我不知道如何选择...... – NullBy7e

0
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 

获得其他类型