Interface Properties

In my interface, I declared a property with an installer and getter.

public interface ITestInterface
{
   string AProperty { get; set; }
}

When I code my class that inherits this interface, why do I need to define these two properties again?

public sealed class MyClass: ITestInterface
{
   public string AProperty { get; set; }
}
+4
source share
7 answers

Since you are not inheriting from an interface, you are implementing an interface. (although both have the same syntax :)

public class MyClass : IMyInterface { ... } //interface implementing
public class MyClass : MyBaseClass { ... } //inheriting from a class

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

+4

, , . , .

:

public sealed class MyClass: ITestInterface
{
    public string APROPERTY
    {
        get { return someField + " hello"; }
        set { someOtherField = value; }
    }
}

string AProperty { get; set; } , , .

+2

-. .

, - . : -?

, ( : ++) .

, . , - 1, , 1. -, , . vtable ( . ).

, ++, VTables : vtable, , "". , , . (, ), ++ "".

"", , , . , , , "" . , (RPC) , ..

++ ( ) . , "" , "" #, , . , vtable, , .

, . , - ( #):

interface A { Foo(); } // basically an interface.
interface B : A { Foo(); } // another interface
class B : A { void Foo() {...} } // implementation of Foo, inherits A
class D : B,C { } // inherits both B, C (and A via both B and C).

, , Foo D. vtable D. vtable :

Foo() -> C::Foo()

, D Foo, Foo C:

var tmp = new D();
tmp.Foo(); // calls C::Foo()

, B - :

class B : A { void Foo() {...} } // changed into an implementation

, vtable D, :

Foo() -> C::Foo() or B::Foo()???

, : Foo ? , ? ? ++ .

.NET # , , . , , .

, ( ) .

+2

, . , ITestInterface get AProperty. . this this.

0

, , . AProperty { get; set; } , .

, .

public interface ITestInterface
{
    string AProperty { get; set; }
}

, .

public sealed class MyClass: ITestInterface
{
    public string AProperty { get; set; }
}

, ( ).

0

, - . , , . , , , .

, :

public interface ITestInterface
{
    string AProperty { get; }
}

, :

class MyClass : ITestInterface
{
   public string AProperty { get { if (DateTime.Today.Day > 7) return "First week of month has past"; return "First week of month is on"; } }
}

setter , , ({get; set;}). , .

, , , , ( ) ( ), .

0

, - , auto ( get set) . - () , , . , .

= ; class= .

public interface ITestInterface
{
   string GetAProperty();
}

public class MyClass : ITestInterface
{
    public string GetAProperty()
    {
        // Do work...
        return "Value";
    }
}
0

All Articles