在C#中的内部类中实现内部接口

时间:2022-04-26 05:00:14

Why can't I implement an internal interface in an internal class?

为什么我不能在内部类中实现内部接口?

internal interface IDefinition
{
    string GetValueAsString(string property);
}

internal sealed class DefinitionArray : IDefinition
{
    internal string GetValueAsString(string property)
    {
        return m_definitionRows
            .Select(o => o.GetValueAsString(property))
            .FirstOrDefault();
    }
}

2 个解决方案

#1


2  

§3.5.6 of the C# 6.0 Language Specification states:

§3.5.6的C#6.0语言规范声明:

Interface members implicitly have public declared accessibility. No access modifiers are allowed on interface member declarations.

接口成员隐式具有公共声明的可访问性。接口成员声明中不允许访问修饰符。

So what you 'theoretically' have is

所以你在理论上拥有的是

internal interface IDefinition
{
    public string GetValueAsString(string property);
}

But this is not a problem, since (§3.5.2):

但这不是问题,因为(§3.5.2):

The accessibility domain of a nested member M declared in a type T within a program P is defined as follows (noting that M itself may possibly be a type):

在程序P中的类型T中声明的嵌套成员M的可访问域定义如下(注意M本身可能是类型):

  • If the declared accessibility of M is public, the accessibility domain of M is the accessibility domain of T.
  • 如果M的声明可访问性是公共的,则M的可访问域是T的可访问域。

So the accessibility of the member is equivalent as it would have been declared as internal.

因此,成员的可访问性与已声明为内部的相同。

#2


1  

The members that make up the Interface's implementation must be public. Even if they are public since the class is internal it's only available to the proper assembly.

构成Interface实现的成员必须是公共的。即使它们是公开的,因为课程是内部的,它只适用于正确的组装。

#1


2  

§3.5.6 of the C# 6.0 Language Specification states:

§3.5.6的C#6.0语言规范声明:

Interface members implicitly have public declared accessibility. No access modifiers are allowed on interface member declarations.

接口成员隐式具有公共声明的可访问性。接口成员声明中不允许访问修饰符。

So what you 'theoretically' have is

所以你在理论上拥有的是

internal interface IDefinition
{
    public string GetValueAsString(string property);
}

But this is not a problem, since (§3.5.2):

但这不是问题,因为(§3.5.2):

The accessibility domain of a nested member M declared in a type T within a program P is defined as follows (noting that M itself may possibly be a type):

在程序P中的类型T中声明的嵌套成员M的可访问域定义如下(注意M本身可能是类型):

  • If the declared accessibility of M is public, the accessibility domain of M is the accessibility domain of T.
  • 如果M的声明可访问性是公共的,则M的可访问域是T的可访问域。

So the accessibility of the member is equivalent as it would have been declared as internal.

因此,成员的可访问性与已声明为内部的相同。

#2


1  

The members that make up the Interface's implementation must be public. Even if they are public since the class is internal it's only available to the proper assembly.

构成Interface实现的成员必须是公共的。即使它们是公开的,因为课程是内部的,它只适用于正确的组装。