简体   繁体   中英

Generic Interface with property

i have one interface

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

Now I want to implement this interface in my class

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

I don't want to implement it like

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

I want to implement it like

public string Text
{
    get{} set {}
}

You are free to do this. This is an implicit interface implementation.

The following is valid C#:

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

public class MyTextBox : IBindable<string>
{

    public string Text
    {
        get;
        set;
    }
}

When you implement an interface, you are free to implement it implicitly, as above, or explicitly, which would be your second option:

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

The difference is in usage. When you use the first option, the Text property becomes a publicly visible property on the type itself ( MyTextBox ). This allows:

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

However, if you implement it explicitly, you need to be using your interface directly:

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

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