2008-09-26 2 views

답변

9

Type.InvokeMember도 있습니다.

public static class ReflectionExt 
{ 
    public static object GetAttr(this object obj, string name) 
    { 
     Type type = obj.GetType(); 
     BindingFlags flags = BindingFlags.Instance | 
           BindingFlags.Public | 
           BindingFlags.GetProperty; 

     return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null); 
    } 
} 
처럼 사용될 수

(확장 법 등)

object value = ReflectionExt.GetAttr(obj, "PropertyName"); 
또는

:

object value = obj.GetAttr("PropertyName"); 
3

이에 대한 반성을 사용하십시오.

Type.GetProperty()Type.GetProperties() 각각은 객체의 속성 값을 읽는 데 사용할 수있는 PropertyInfo 인스턴스를 반환합니다.

var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null) 

Type.GetMethod()Type.GetMethods() 및 각 객체의 메소드를 실행하는데 사용될 수 MethodInfo 인스턴스를 반환한다.

var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null); 

당신은 반드시 여러분이이 같은 일을 할 수있는 것보다, (당신은 속성 이름을 새 경우 조금 이상한 것) 유형을 모르는 경우.

var result = dt.GetType().GetProperty("Year").Invoke(dt, null); 
1

예, 당신이 할 수있는 ...

typeof(YourObjectType).GetProperty("PropertyName").GetValue(instanceObjectToGetPropFrom, null); 
0

object.GetType를 사용하여 생성 할 수 System.Reflection.PropertyInfo 클래스가있다(). GetProperties를(). 이를 사용하여 문자열을 사용하여 객체의 속성을 검사 할 수 있습니다. (객체 메서드, 필드 등에 대해서도 비슷한 메서드가 있습니다.)

당신의 목표를 달성하는 데 도움이 될 것이라고 생각하지 않습니다. 아마도 객체를 직접 생성하고 조작해야합니다. 컨트롤에는 예를 들어 설정할 수있는 Name 속성이 있습니다.

관련 문제