Can a C # interface require or dictate a specific class?

Is it possible to declare an interface (i.e., IMySpecialControl) that requires classes that implement it to also inherit from some base class (e.g. System.Windows.Controls.UserControl)?

I think no, that’s not possible. But it would be very convenient to write client code in such a way that it only accepts "IMySpecialControl", which defines several members that it cares about, and that it can count on the fact that this object is also a UserControl, which it can then add to the graphical interface or to manipulate.

I know that I can always check whether an instance of an object defined as "IMySpecialControl" is also a UserControl, but I was hoping that in .Net I did not know. :-)

+4
source share
2 answers

Is it possible to declare an interface (i.e., IMySpecialControl) that requires classes that implement it to also inherit from some base class (e.g. System.Windows.Controls.UserControl)?

No, in C # there is nothing that defines this.

Perhaps it would be easier to create an abstract subclass UserControl.

What you can do is have a generic method or type with the restriction that the type parameter implements the interface and is compatible with the class:

public void Foo<T>(T control) where T : UserControl, IMySpecialControl

I do not know how useful this is in your particular case, but it is the closest to your initial requirement.

+8
source

- , - . MSDN:

, , .

, # , , . ? # true Multiple Inheritance. , , - . , # - ? , , .

Java Single Multiple Inheritance. , (++), , ; , .. - , ( ) , .

, , , . , , , . ( ) , . .

, , , . :

public interface IMySpecialControl
{
    string SpecialData { get; set; }
    int UniqueNumber { get; set; }
}

public static class MySpecialControlExtension
{
    public static string SpecialUniqueDataNumber(this IMySpecialControl control)
    {
        return control.SpecialData + control.UniqueNumber.ToString();
    }
}

public class Special : IMySpecialControl
{
    public string SpecialData { get; set; }
    public int UniqueNumber { get; set; }
}

IMySpecialControlExtension SpecialUniqueDataNumber :

var specialInstance = new Special();
specialInstance.SpecialData = "Pi is exactly equal to: ";
specialInstance.UniqueNumber = 3;

// Note not passing a paramater for the instance to the extension method.
// It intentionally looks like a method of the class being extended,
//  both when reading the source and in intellisense.
Console.WriteLine(specialInstance.SpecialUniqueDataNumber()); 
+1

All Articles