滅入るんるん

何か書きます

Kotlin使いのためのC#入門 Interfaces

> Top

C#にもKotlin同様にinterfaceが存在します。また、interfaceのメンバーには自動的にpublicの可視性となります。

interface IValue
{
    void FromString(string value);
}

Implementing Interfaces

C#にもoverride修飾子は存在しますが、interfaceのメンバーを実装する際は付けません。また、現在のところC#のinterfaceにはデフォルト実装を持たせることはできませんが、今後のアップデートで追加される見通しです。

class Value : IValue
{
    public void FromString(string value)
    {
        throw new NotImplementedException();
    }
}

Properties in Interfaces

プロパティは仕組み上はメソッドのようなもののため、interfaceに定義することもできます。

interface IValue
{
    string Text { get; set; }
}

class Value : IValue
{
    public string Text { get; set; }
}

Interfaces Inheritance

もちろん、interfaceは継承することもできます。

interface IView
{

}

interface IMainView : IView
{

}

class MainView : IMainView
{

}

Resolving overriding conflicts

interfaceの多重実装を許しているとメンバーのシグネチャーが重なることがあります。その場合はinterfaceの明示的な実装を行うことによって、衝突を回避することができます。

interface IUser
{
    int Id { get; }
}

interface IStatus
{
    int Id { get; }
}

class UserAndStatus : IUser, IStatus
{
    int IUser.Id { get; }
    int IStatus.Id { get; }

    public void Main()
    {
        // 明示的な実装をした場合はinterface経由でアクセスする必要がある
        int id = ((IUser)this).Id;
    }
}