简体   繁体   中英

Using an interface to communicate back to a Generic Type class that manages objects with this interface

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);
}

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM