1

아래의 모든 public 속성을 가져 오려고합니다. 는 .NET 프레임 워크에서 나는 PropertyInfo 유형에서 IsPublic을 사용하여 해당에 거라고하지만 그건 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하지 중복 다른 유형을 얻을 수 있습니다. – NullBy7e

+0

@mjwills 저는 여기서 잘못했습니다. 나는 질문을 편집하고 더 명확하게했습니다. – NullBy7e

답변

1

대안 .. 따라서, 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; } 
    } 
,536,

이렇게하면 public int YearsExperience 만 성공적으로 반환됩니다.

+0

그게 작동하지 않는 것, 모든 상속 된 유형의 모든 공용 속성을 반환합니다. – NullBy7e

+0

@ NullBy7e 업데이트 답변. –

+0

감사합니다. 작동하는 것 같습니다! 아래의 답변도 작동하지만 평판이 낮기 때문에 대답으로 표시 할 것입니다. – NullBy7e

2

당신은 "클래식"에서와 같이 바인딩 플래그를 사용할 수있는 .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); 
+0

작동하지 않는 것처럼 보입니다. 열거 형은'BindingFlags.Public'만으로 비어 있으며 두 플래그 일 때 상속 된 onces를 포함한 모든 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); 
    } 
} 

을 지정할 수 있습니다 즉 SO 대답은 .NET 코어 2.0 (Apparantly 히) 작동하지 않습니다 TypeExtensions를 권장하기 때문에

BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance