2017-09-16 144 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 

獲得其他類型