I have a generic type class called
public class ScrollClippingViewer<T> where T : Control, IFScrollClippingItem
This class will handle different kinds of UserControls that also inherit IFScrollClippingItem
. It will store the UserControls in a list, and makes sure they are displayed in order in a ScrollViewer.
What I would like is that a UserControl would have a property or method in the interface that creates the possibility to communicate back to the ScrollClippingViewer; My problem rises because the ScrollClippingViewer is a generic type class and I dont know how to put this in the interface:
public interface IFScrollClippingItem
{
// This does not work
ScrollClippingViewer<T> refScrollClippingViewer { get; set; }
// This neither
void SetScrollClippingViewer(ScrollClippingViewer<T> argRefScrollClippingViewer);
}
CodePudding user response:
You can have templated method in your interface, like this:
public interface IFScrollClippingItem
{
void SetScrollClippingViewer<T>(ScrollClippingViewer<T> argRefScrollClippingViewer) where T: Control, IFScrollClippingItem;
}
but it doesn't seem to be good idea, because template type T
has no connection with interface, so when implementing interface you'll write something like:
public class SampleControl: Control, IFScrollClippingItem
{
public void SetScrollClippingViewer<T>(ScrollClippingViewer<T> argRefScrollClippingViewer) where T: Control, IFScrollClippingItem
{
...
}
}
In this method you'll be able to work with argRefScrollClippingViewer
passed, but you won't be able to save it to a typed property, as long as there can't be property of type ScrollClippingViewer<T>
.
I would recommend you to introduce some interface: IScrollClippingViewer
which will be implemented by ScrollClippingViewer
and will provide needed functions for IFScrollClippingItem
instances.
For example:
public interface IScrollClippingViewer
{
...
}
public class ScrollClippingViewer<T>: IScrollClippingViewer where T: Control, IFScrollClippingItem
{
...
}
public interface IFScrollClippingItem
{
IScrollClippingViewer Viewer { get; set; }
}
CodePudding user response:
It works in this simple way.
public interface IFScrollClippingItem
{
// This does not work
IFScrollClippingItem refScrollClippingViewer { get; set; }
}
Obviously, if a client needs the generic class have to cast refScrollClippingViewer
with the appropriate generic type.