簡體   English   中英

具有屬性的通用接口

[英]Generic Interface with property

我有一個界面

/// <summary>
/// Summary description for IBindable
/// </summary>
public interface IBindable<T>
{
    // Property declaration:
    T Text
    {
        get;
        set;
    }
}

現在我想在我的課堂上實現這個接口

public class MyTextBox :IBindable<string>
{
    //now i how can i implement Text peroperty here 
}

我不想像這樣實現

string IBindable<string>.Text
{  
    get { return "abc";} 
    set { //assigne value } 
}

我想像實施

public string Text
{
    get{} set {}
}

您可以自由地這樣做。 這是一個隱式接口實現。

以下是有效的C#:

public interface IBindable<T>
{
    // Property declaration:
    T Text
    {
        get;
        set;
    }
}

public class MyTextBox : IBindable<string>
{

    public string Text
    {
        get;
        set;
    }
}

當實現接口時,您可以自由地隱式地(如上所述)或顯式地實現它,這是您的第二個選擇:

string IBindable<string>.Text
{  get { return "abc";} set { // assign value } }

區別在於用法。 使用第一個選項時, Text屬性將成為類型本身( MyTextBox )上的公共可見屬性。 這允許:

MyTextBox box = new MyTextBox();
box.Text = "foo";

但是,如果您明確實現它,則需要直接使用您的接口:

MyTextBox box = new MyTextBox();
IBindable<string> bindable = box;
box.Text = "foo"; // This will work in both cases
public class MyTextBox : IBindable<string>
{
    //now i how can i implement Text peroperty here 
    public string Text
    {
        get;
        set;
    }
}

暫無
暫無

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

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