programing tip

클래스에 속성이 있는지 확인

itbloger 2020. 10. 27. 07:55
반응형

클래스에 속성이 있는지 확인


클래스에 속성이 있는지 확인하려고 시도했습니다.

public static bool HasProperty(this object obj, string propertyName)
{
    return obj.GetType().GetProperty(propertyName) != null;
}

첫 번째 테스트 방법이 통과하지 못하는 이유를 이해할 수 없습니까?

[TestMethod]
public void Test_HasProperty_True()
{
    var res = typeof(MyClass).HasProperty("Label");
    Assert.IsTrue(res);
}

[TestMethod]
public void Test_HasProperty_False()
{
    var res = typeof(MyClass).HasProperty("Lab");
    Assert.IsFalse(res);
}

방법은 다음과 같습니다.

public static bool HasProperty(this object obj, string propertyName)
{
    return obj.GetType().GetProperty(propertyName) != null;
}

이것은 모든 것의object 기본 클래스에 확장을 추가합니다 . 이 확장을 호출하면 다음과 같이 전달됩니다 .Type

var res = typeof(MyClass).HasProperty("Label");

귀하의 방법은 예상 예를 클래스가 아닌의를 Type. 그렇지 않으면 본질적으로

typeof(MyClass) - this gives an instanceof `System.Type`. 

그때

type.GetType() - this gives `System.Type`
Getproperty('xxx') - whatever you provide as xxx is unlikely to be on `System.Type`

로 @PeterRitchie 올바르게 코드가 재산을 찾고있는이 시점에서, 지적 LabelSystem.Type. 해당 속성이 존재하지 않습니다.

해결책은

a) 확장에 MyClass 인스턴스제공합니다 .

var myInstance = new MyClass()
myInstance.HasProperty("Label")

b) 내선을 System.Type

public static bool HasProperty(this Type obj, string propertyName)
{
    return obj.GetProperty(propertyName) != null;
}

typeof(MyClass).HasProperty("Label");

이것은 다른 질문에 답합니다.

OBJECT (클래스 아님)에 속성이 있는지 알아 내려고하면

OBJECT.GetType().GetProperty("PROPERTY") != null

속성이 존재하는 경우에만 true를 반환합니다.

제 경우에는 ASP.NET MVC 부분보기에 있었고 속성이 존재하지 않거나 속성 (부울)이 true 인 경우 무언가를 렌더링하고 싶었습니다.

@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
        Model.AddTimeoffBlackouts)

여기에서 나를 도왔다.

편집 : 요즘에는 nameof문자열 속성 이름 대신 연산자 를 사용하는 것이 현명 할 것입니다 .


두 가지 가능성이 있습니다.

당신은 정말 Label재산 이 없습니다 .

적절한 GetProperty 오버로드 를 호출 하고 올바른 바인딩 플래그를 전달해야합니다. 예 :BindingFlags.Public | BindingFlags.Instance

속성이 공개되지 않은 BindingFlags.NonPublic경우 사용 사례에 맞는 플래그를 또는 다른 조합으로 사용해야합니다. 참조 된 API 문서를 읽고 세부 사항을 찾으십시오.

편집하다:

ooops, just noticed you call GetProperty on typeof(MyClass). typeof(MyClass) is Type which for sure has no Label property.


I got this error: "Type does not contain a definition for GetProperty" when tying the accepted answer.

This is what i ended up with:

using System.Reflection;

if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{

}

If you are binding like I was:

<%# Container.DataItem.GetType().GetProperty("Property1") != null ? DataBinder.Eval(Container.DataItem, "Property1") : DataBinder.Eval(Container.DataItem, "Property2")  %>

I'm unsure of the context on why this was needed, so this may not return enough information for you but this is what I was able to do:

if(typeof(ModelName).GetProperty("Name of Property") != null)
{
//whatevver you were wanting to do.
}

In my case I'm running through properties from a form submission and also have default values to use if the entry is left blank - so I needed to know if the there was a value to use - I prefixed all my default values in the model with Default so all I needed to do is check if there was a property that started with that.

참고URL : https://stackoverflow.com/questions/15341028/check-if-a-property-exist-in-a-class

반응형