与属性的通用接口

Pra*_*ana -1 c#

我有一个界面

/// <summary>
/// Summary description for IBindable
/// </summary>
public interface IBindable<T>
{
    // Property declaration:
    T Text
    {
        get;
        set;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想在我的类中实现这个接口

public class MyTextBox :IBindable<string>
{
    //now i how can i implement Text peroperty here 
}
Run Code Online (Sandbox Code Playgroud)

我不想像它那样实现它

string IBindable<string>.Text
{  
    get { return "abc";} 
    set { //assigne value } 
}
Run Code Online (Sandbox Code Playgroud)

我想像它一样实现它

public string Text
{
    get{} set {}
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 5

你可以自由地做到这一点.这是一个隐式接口实现.

以下是有效的C#:

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

public class MyTextBox : IBindable<string>
{

    public string Text
    {
        get;
        set;
    }
}
Run Code Online (Sandbox Code Playgroud)

当您实现一个接口时,您可以像上面那样隐式地实现它,也可以显式地实现它,这将是您的第二个选择:

string IBindable<string>.Text
{  get { return "abc";} set { // assign value } }
Run Code Online (Sandbox Code Playgroud)

不同之处在于使用方法.当您使用第一个选项时,该Text属性将成为类型本身(MyTextBox)的公开可见属性.这允许:

MyTextBox box = new MyTextBox();
box.Text = "foo";
Run Code Online (Sandbox Code Playgroud)

但是,如果明确实现它,则需要直接使用您的界面:

MyTextBox box = new MyTextBox();
IBindable<string> bindable = box;
box.Text = "foo"; // This will work in both cases
Run Code Online (Sandbox Code Playgroud)