아래 표시된 내 코드는 양식의 모든 시각적 및 비 시각적 구성 요소 (OpenDialogs, SaveDialogs 등)를 보여줍니다. 모든 폼 요소를 아는 것보다 구성 요소 이름 (컨트롤 없음)을 지정할 수 있으면 좋을 것 같습니다.목록 구성 요소 (컨트롤이 아님)
private IEnumerable <Component> EnumerateComponents()
{
return this.GetType() GetFields (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where (F => typeof (Component) .IsAssignableFrom (f.FieldType))
.Where (F => typeof (Control) .IsAssignableFrom (f.FieldType))
//.Where componentName.thatIinformed == "OpenDialog1" <<<<<======
.Select (F => f.GetValue (this))
.OfType <Component>();
}
가능합니까?
public IEnumerable<Component> EnumerateComponents()
{
return this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => typeof(Component).IsAssignableFrom(x.PropertyType))
.Select(x => x.GetValue(this)).Cast<Component>();
}
나는 다음과 같은 사용자 정의 UserControl
와 함께이 시도 :
public sealed class MyCustomControl : UserControl
{
// Adding some Controls for testing
public Label MyLabel1 { get; set; }
public Label MyLabel2 { get; set; }
// Adding a Component (not a Control) for testing
public System.Windows.Forms.Timer MyTimer1 { get; set; }
public IEnumerable<Component> EnumerateComponents()
{
return this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => typeof(Component).IsAssignableFrom(x.PropertyType))
.Select(x => x.GetValue(this)).Cast<Component>();
}
public IEnumerable<PropertyInfo> EnumerateProperties()
{
return this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => typeof(Component).IsAssignableFrom(x.PropertyType));
}
}
EnumerateProperties
방법은 너무 나는 그것을 테스트 할 수 있었다이의 라인을 따라 뭔가 더 원하는처럼
'Control'은'Component'에서 상속되기 때문에 두 번째 where 절은 필요 없습니다. 사실'Component' 레벨 대신'Control'에서 파생 된'Control' 타입과 타입으로 제한됩니다 . 또한, 그것은 당신이 성취하고자하는 것을 완전히 명확하게하지 않습니다. – Anthony
@Anthony, 답변 해 주셔서 감사합니다. 구성 요소 이름을 말할 때 다른 구성 요소의 속성 만 잡을 수 있습니다 (PropertyInfo [] = component.GetProperties PropertyInfo()). – Luana