클래스에 속성이 있는지 확인
클래스에 속성이 있는지 확인하려고 시도했습니다.
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 올바르게 코드가 재산을 찾고있는이 시점에서, 지적 Label
에 System.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
'programing tip' 카테고리의 다른 글
jQuery를 사용하여 선택한 확인란의 값을 가져옵니다. (0) | 2020.10.28 |
---|---|
CoreData에 어레이를 저장하는 방법은 무엇입니까? (0) | 2020.10.28 |
Octave / Matlab : 벡터에 새 요소 추가 (0) | 2020.10.27 |
제네릭 메서드는 어떻게, 언제, 어디서 구체화됩니까? (0) | 2020.10.27 |
dplyr에서 조인 할 때 x 및 y에 대한 열 이름을 지정하는 방법은 무엇입니까? (0) | 2020.10.27 |