Xamarin.Forms: 我可以声明一个必须是 ContentView 的界面吗

Xamarin.Forms: can I declare an interface that has to be a ContentView

我希望在 Xamarin.Forms 中有一个限制为 ContentView 的界面。

我在想这样的事情,但这本身行不通:

public interface InterfaceThatMustBeAContentView : ContentView
    {
        //....interfacey stuff
    }

我已经为此做了很多网络搜索,但我总是 运行 谈论接口继承和子类一致性的事情,这不是我所追求的。

有办法吗?

不,你不能那样做。但是您可以做一些相关的事情,具体取决于您要实现的目标。

public interface IMyThing1
{
    ContentView Thing { get; }
}

public interface IMyThing2<T> where T : ContentView
{
    T Thing { get; }
}

或者如果您只需要它与您自己的 ContentView 一起工作类,并且您不需要接口来保证它可以转换为 ContentView:

public interface IMyThing3
{
    // A few properties and methods that you know anything that inherits from ContentView will have
}

public class MyThing3 : IMyThing3, ContentView
{
}

或者,如果您只需要将 属性 或变量限制为 ContentView,那么您根本不需要接口,只需将其声明或强制转换为 ContentView。

public void DoSomething(ContentView contentView)
{
    ContentView anotherContentView;
    // do something
}

public void DoSomethingToAFrame(Frame frame)
{
    DoSomething(frame);
}

我只能想到这个了。这是一个丑陋的解决方案,但它解决了你的问题。

public interface InterfaceThatMustBeAContentView : 
IControlTemplated
ILayout, ILayoutController, IPaddingElement
IViewController, IGestureController, IGestureRecognizers
IAnimatable, IVisualElementController, IResourcesProvider, IStyleElement, IFlowDirectionController, IPropertyPropagationController, IVisualController, ITabStopElement
INavigationProxy, IStyleSelectable
IElement, INameScope, IElementController
INotifyPropertyChanged, IDynamicResourceHandler 
{
}

Kludgey 可能性

这就像 Robyn 的回答:

public interface IKludgeyContentViewInterface 
{
   ContentView ViewKludge { get; }
}

它不会强制任何内容成为 ContentView,但您可以像这样将它与 ContentView 一起使用:

public ContentViewKludgeySubclass : ContentView, IKludgeyContentViewInterface 
{
   ContentView ViewKludge { get { return this; }; }
}

我知道这有点傻,你觉得呢?