嵌套接口的替代方法(在C#中不可能)

eri*_*des 20 c# interface

我在这种情况下使用接口主要是作为对象的不可变实例的句柄.问题是不允许在C#中嵌套接口.这是代码:

public interface ICountry
{
    ICountryInfo Info { get; }

    // Nested interface results in error message:
    // Error    13  'ICountryInfo': interfaces cannot declare types
    public interface ICountryInfo
    {
        int Population { get; }
        string Note { get; }
    }
}


public class Country : ICountry
{
    CountryInfo Info { get; set; }

    public class CountryInfo : ICountry.ICountryInfo
    {
        int Population { get; set; }
        string Note { get; set; }
        .....
    }
    .....
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找替代方案,任何人都有解决方案吗?

Jor*_*dão 17

VB.NET允许这样做.因此,您只能使用所需的接口定义创建VB.NET程序集:

Public Interface ICountry
  ReadOnly Property Info() As ICountryInfo

  Public Interface ICountryInfo
    ReadOnly Property Population() As Integer
    ReadOnly Property Note() As String
  End Interface
End Interface
Run Code Online (Sandbox Code Playgroud)

至于实现,C#不支持协变返回类型,所以你必须像这样声明你的类:

public class Country : ICountry {
  // this property cannot be declared as CountryInfo
  public ICountry.ICountryInfo Info { get; set; }

  public class CountryInfo : ICountry.ICountryInfo {
    public string Note { get; set; }
    public int Population { get; set; }
  }
}
Run Code Online (Sandbox Code Playgroud)