, questionner은 UIElement에 기반을 선언하는 추상 클래스
보기의 일반적인 모범 사례 및 정확성 관점에서
, 당신 에게서는와 상속의 hierachies을 작성하기위한 최상의 방법에 대한 조언을 찾고있다 생성자와 추상화자가없는 클래스. 예 :
public abstract class UIElement
{
//constructor
protected UIElement();
//draw element
public abstract void Draw(int mouseX, int mouseY);
//checks if the element is pointed at by mouse
public abstract bool IsPointed(int mouseX, int mouseY);
//defines what happens when clicked
public abstract void Click(int mouseX, int mouseY);
}
당신이 수 후 당신은 위의에 따라 파생 된 클래스를 정의하는 경우, 당신은 기본 유형의 배열로 요소와 저장소를 인스턴스화 할 수 올바른
public class UIElementButton : UIElement
{
// Optional - create parameterless constructor and
// explicitly call base constructor
public UIElementButton() : base()
{
}
// Mandatory - must override abstract methods
public override Draw(int mouseX, int mouseY)
{
}
// Mandatory - must override abstract methods
public override Boolean IsPointed(int mouseX, int mouseY)
{
}
// Mandatory - must override abstract methods
public override void Click(int mouseX, int mouseY)
{
}
}
을 다음과 같이 파생 클래스를 구현 다음과 같습니다 :
UIElement[] qwe = new UIElement[3];
qwe[0] = new UIElementButton();
qwe[1] = new UIElementLabel();
qwe[2] = new UIElementSomethingElse();
qwe[0].Click(1, 2); // Invokes UIElementButton.Click
qwe[1].Draw(3, 4); // Invokes UIElementLabel.Draw
또한 WPF에 정의 된 UIElement 클래스가 있어야합니다. 유형에 대한 네임 스페이스를 정의하는 경우 문제가되지 않지만 사용자 정의 유형을 구별하기 위해보다 명확한 유형 이름 (예 : BaseElement
)을 고려하십시오. 의견의 쿼리에 대해서는
:
추상 클래스의 사용에 대한 자세한 조언을 들어, All about abstract classes - Codeproject를 참조하십시오. - 클래스 변수는 어디에서 선언해야합니까? 기본 클래스 또는 파생 클래스? - 다른 파생 클래스에 다른 변수가있는 경우 어떻게 처리해야합니까? - 파생 클래스가 다른 인수를 포함하여 다른 생성자를 가질 수 있습니까?
이들은 그러나 선발로 내가 말할 수있는, 정말 구글에 다른 질문이나 자신의 연구에 대한 주제입니다
클래스 변수들이 필요한 범위에서 선언해야합니다. 변수가 Guid _uiElementId
이고 파생 형식에서 액세스하려고하는 경우 기본 클래스에서 선언하고 protected
으로 표시해야합니다. 당신이있는 경우 UIElementButton의 변수는 Point _mousePoint
이라고 만 UIElement에 버튼 괜찮아 private
로이 마크에두고, 그것을 필요 - 기본 클래스에서 자신의 개인 변수와 보호 변수를 볼 수있는 유형입니다. 이름이 충돌하지 않는지 확인하십시오.
예.
public class UIElementButton : UIElement
{
private string _buttonText;
// Overloaded ctor
public UIElementButton(string buttonText) : base()
{
buttonText = buttonText;
}
// Default constructor. Mark as private or protected
// to hide from external API
public UIElementButton() : base()
{
}
}
안부
, 그것은이 문제이지만, 코드가 컴파일되지 않습니다 귀하의 질문에서 명확하지
실제로 명확하지는 않지만 실제로 무엇을하고 있습니다. – kkm
그게 뭐가 잘못 됐니? 귀하의 코드가 올바른 것 같습니다. 제가 지적하고자하는 유일한 사실은 추상 소멸자에 대한 사용이 거의 없다는 것입니다. 대신에'IDisposable'을 대신 구현해야합니다. –
@kkm, 결코 덜 작동하지 않습니다 :) – NewProger