簡體   English   中英

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
    }

我已經完成 web 搜索了很多,但我總是遇到談論接口 inheritance 和子類一致性的事情,這不是我所追求的。

有沒有辦法做到這一點?

不,你不能那樣做。 但是你可以做一些相關的事情,這取決於你想要實現的目標。

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

混亂的可能性

這就像羅賓的回答:

public interface IKludgeyContentViewInterface 
{
   ContentView ViewKludge { get; }
}

而且它不會強制任何內容成為 ContentView,但您可以將它與 ContentView 一起使用,如下所示:

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

我知道這有點愚蠢,你怎么看?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM