I cannot find what I am looking for and am new to many of the features of C#. Basically I have a class with lots of methods, many of which pertain to similar manipulations. I am writing a sort of API and would like the end user to be able to access these methods by grouping them by purpose.
So my class has many members that all access the same data, lets call it ParentClass, and I would like to call ParentClass.ZoomFunctions.ZoomIn() where zoom in accessed data in the parent class (and is preferably a member of 开发者_开发知识库that class.)
I don't have a good idea of how to use inheritance, but I could not find how to do this simply.
Hmm...
Without know more about your code, it sounds like your class is trying to do too much. Perhaps you should consider breaking your API into multiple classes instead of trying to group methods in a class.
Consider reading about Single Responsibility Principle
and Separation of Concerns
to see how your class design could be improved.
It sounds like you should create an interface which groups together your methods, then create a public property with the interface as its type.
For example:
interface IZoomFunctions
{
public void ZoomIn();
...
}
class ParentClass : IZoomFunctions
{
public IZoomFunctions ZoomFunctions { get; }
}
If you want to be sure that your users access the functions only through your defined paths (i.e. they have to call ParentClass.ZoomFunctions.ZoomIn() and shouldn't be allowed to call ParentClass.ZoomIn() directly), and if you want to keep all your stuff together in a single class, without creating different classes, you can:
define an interface for each of your groups of methods, just like JohnD suggested:
public interface IZoomFunctions
{
public void ZoomIn();
//...
}
add to your parent class a property which returns the class itself cast to your interface:
public IZoomFunctions ZoomFunctions
{
get { return this as IZoomFunctions; }
}
then make your class explicitly implement the interface and make the original methods private (to avoid direct access):
class ParentClass : IZoomFunctions
{
// your stuff
public IZoomFunctions ZoomFunctions
{
get { return this as IZoomFunctions; }
}
private void ZoomIn()
{
// your real code here
}
public void IZoomFunctions.ZoomIn()
{
this.ZoomIn();
}
}
精彩评论