리플렉션을 사용하여 정적 속성을 얻는 방법
그래서 이것은 매우 기본적인 것처럼 보이지만 작동하도록 할 수 없습니다. 객체가 있고 반사를 사용하여 공용 속성을 얻습니다. 이러한 속성 중 하나는 정적이며 운이 좋지 않습니다.
Public Function GetProp(ByRef obj As Object, ByVal propName as String) as PropertyInfo
Return obj.GetType.GetProperty(propName)
End Function
위의 코드는 Public Instance 속성에 대해 잘 작동하며 지금까지 필요한 모든 것입니다. 아마도 BindingFlags를 사용하여 다른 유형의 속성 (개인, 정적)을 요청할 수 있지만 올바른 조합을 찾을 수없는 것 같습니다.
Public Function GetProp(ByRef obj As Object, ByVal propName as String) as PropertyInfo
Return obj.GetType.GetProperty(propName, Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public)
End Function
그러나 여전히 정적 멤버를 요청하면 아무것도 반환되지 않습니다. .NET 리플렉터는 정적 속성을 잘 볼 수 있으므로 여기에 뭔가 누락되었습니다.
아니면 이것 좀보세요 ...
Type type = typeof(MyClass); // MyClass is static class with static properties
foreach (var p in type.GetProperties())
{
var v = p.GetValue(null, null); // static classes cannot be instanced, so use null...
}
이것은 C #이지만 아이디어를 제공해야합니다.
public static void Main() {
typeof(Program).GetProperty("GetMe", BindingFlags.NonPublic | BindingFlags.Static);
}
private static int GetMe {
get { return 0; }
}
(또는 NonPublic 및 Static에만 필요)
약간의 명확성 ...
// Get a PropertyInfo of specific property type(T).GetProperty(....)
PropertyInfo propertyInfo;
propertyInfo = typeof(TypeWithTheStaticProperty)
.GetProperty("NameOfStaticProperty", BindingFlags.Public | BindingFlags.Static);
// Use the PropertyInfo to retrieve the value from the type by not passing in an instance
object value = propertyInfo.GetValue(null, null);
// Cast the value to the desired type
ExpectedType typedValue = (ExpectedType) value;
좋아, 나에게 핵심은 .FlattenHierarchy BindingFlag를 사용하는 것이 었습니다. 왜 내가 직감으로 추가했고 작동하기 시작한 이유를 모르겠습니다. 따라서 공개 인스턴스 또는 정적 속성을 얻을 수있는 최종 솔루션은 다음과 같습니다.
obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
Reflection.BindingFlags.FlattenHierarchy)
myType.GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
이것은 정적 기본 클래스 또는 특정 유형 및 아마도 자식의 모든 정적 속성을 반환합니다.
(대상 프레임 워크에 따라) 안정적으로 사용할 수없는 TypeInfo
위치를 기반으로하는 새로운 리플렉션 API를 사용하면서 이것을 직접 명확히하고 싶었습니다 BindingFlags
.
'new'리플렉션에서 유형 (기본 클래스 제외)의 정적 속성을 얻으려면 다음과 같이해야합니다.
IEnumerable<PropertyInfo> props =
type.GetTypeInfo().DeclaredProperties.Where(p =>
(p.GetMethod != null && p.GetMethod.IsStatic) ||
(p.SetMethod != null && p.SetMethod.IsStatic));
읽기 전용 또는 쓰기 전용 속성을 모두 충족합니다 (쓰기 전용이 끔찍한 아이디어 임에도 불구하고).
The DeclaredProperties
member, too doesn't distinguish between properties with public/private accessors - so to filter around visibility, you then need to do it based on the accessor you need to use. E.g - assuming the above call has returned, you could do:
var publicStaticReadable = props.Where(p => p.GetMethod != null && p.GetMethod.IsPublic);
There are some shortcut methods available - but ultimately we're all going to be writing a lot more extension methods around the TypeInfo
query methods/properties in the future. Also, the new API forces us to think about exactly what we think of as a 'private' or 'public' property from now on - because we must filter ourselves based on individual accessors.
The below seems to work for me.
using System;
using System.Reflection;
public class ReflectStatic
{
private static int SomeNumber {get; set;}
public static object SomeReference {get; set;}
static ReflectStatic()
{
SomeReference = new object();
Console.WriteLine(SomeReference.GetHashCode());
}
}
public class Program
{
public static void Main()
{
var rs = new ReflectStatic();
var pi = rs.GetType().GetProperty("SomeReference", BindingFlags.Static | BindingFlags.Public);
if(pi == null) { Console.WriteLine("Null!"); Environment.Exit(0);}
Console.WriteLine(pi.GetValue(rs, null).GetHashCode());
}
}
Try this C# Reflection link.
Note I think that BindingFlags.Instance and BindingFlags.Static are exclusive.
참고URL : https://stackoverflow.com/questions/451453/how-to-get-a-static-property-with-reflection
'IT박스' 카테고리의 다른 글
드롭 다운 메뉴에 몇 개의 옵션이 있는지 어떻게 확인합니까? (0) | 2020.08.16 |
---|---|
양식 작업을 변경하는 Jquery (0) | 2020.08.16 |
GDB를 사용하여 실행중인 프로세스를 디버깅 할 수 있습니까? (0) | 2020.08.16 |
이미지가있는 WPF 버튼 (0) | 2020.08.16 |
ReCaptcha API v2 스타일링 (0) | 2020.08.16 |