ArabirimlerInterfaces

Arabirim, bir sözleşmeyi tanımlar.An interface defines a contract. Arabirim uygulayan bir sınıf veya yapı, sözleşmesine uymalıdır.A class or struct that implements an interface must adhere to its contract. Bir arabirim birden çok temel arabirimden devralınabilir ve bir sınıf ya da yapı birden çok arabirim uygulayabilir.An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces.

Arabirimler Yöntemler, özellikler, olaylar ve Dizin oluşturucular içerebilir.Interfaces can contain methods, properties, events, and indexers. Arabirimin kendisi tanımladığı Üyeler için uygulama sağlamaz.The interface itself does not provide implementations for the members that it defines. Arabirim yalnızca arabirimi uygulayan sınıflar veya yapılar tarafından sağlanması gereken üyeleri belirtir.The interface merely specifies the members that must be supplied by classes or structs that implement the interface.

Arabirim bildirimleriInterface declarations

İnterface_declaration , yeni bir arabirim türü bildiren bir type_declaration (tür bildirimleri).An interface_declaration is a type_declaration (Type declarations) that declares a new interface type.

interface_declaration
    : attributes? interface_modifier* 'partial'? 'interface'
      identifier variant_type_parameter_list? interface_base?
      type_parameter_constraints_clause* interface_body ';'?
    ;

İnterface_declaration , isteğe bağlı bir öznitelik kümesinden (öznitelikler) ve ardından isteğe bağlı bir interface_modifier s kümesiyle (arabirim değiştiricileri) oluşur. sonra isteğe bağlı bir değiştirici, ardından bir isteğe bağlı partial interface variant_type_parameter_list belirtimi (Varyant türü parametre listeleri) ve ardından isteğe bağlı bir interface_base belirtimi (temel arabirimler) ve ardından isteğe bağlı bir type_parameter_constraints_clause s belirtimi (tür parametresi kısıtlamaları) ve ardından bir interface_body (arabirim gövdesi) ve daha sonra noktalı virgül gelen bir tanımlayıcı gelir.An interface_declaration consists of an optional set of attributes (Attributes), followed by an optional set of interface_modifier s (Interface modifiers), followed by an optional partial modifier, followed by the keyword interface and an identifier that names the interface, followed by an optional variant_type_parameter_list specification (Variant type parameter lists), followed by an optional interface_base specification (Base interfaces), followed by an optional type_parameter_constraints_clause s specification (Type parameter constraints), followed by an interface_body (Interface body), optionally followed by a semicolon.

Arabirim değiştiricileriInterface modifiers

İnterface_declaration , isteğe bağlı olarak bir arabirim değiştiricileri sırası içerebilir:An interface_declaration may optionally include a sequence of interface modifiers:

interface_modifier
    : 'new'
    | 'public'
    | 'protected'
    | 'internal'
    | 'private'
    | interface_modifier_unsafe
    ;

Aynı değiştiricinin bir arabirim bildiriminde birden çok kez görünmesi için derleme zamanı hatası vardır.It is a compile-time error for the same modifier to appear multiple times in an interface declaration.

newDeğiştiriciye yalnızca bir sınıf içinde tanımlanan arabirimlerde izin verilir.The new modifier is only permitted on interfaces defined within a class. Arabirimin, Yeni değiştiricibölümünde açıklandığı gibi, devralınan bir üyeyi aynı adla gizlediğini belirtir.It specifies that the interface hides an inherited member by the same name, as described in The new modifier.

public,, protected internal Ve private değiştiricileri arabirimin erişilebilirliğini denetler.The public, protected, internal, and private modifiers control the accessibility of the interface. Arabirim bildiriminin gerçekleştiği içeriğe bağlı olarak, bu değiştiricilerin yalnızca bazılarına izin verilebilir (belirtilen erişilebilirlik).Depending on the context in which the interface declaration occurs, only some of these modifiers may be permitted (Declared accessibility).

Kısmi değiştiriciPartial modifier

partialDeğiştirici, bu interface_declaration kısmi bir tür bildirimi olduğunu gösterir.The partial modifier indicates that this interface_declaration is a partial type declaration. Bir kapsayan ad alanı veya tür bildiriminde aynı ada sahip birden çok kısmi arabirim bildirimi, kısmi türlerdebelirtilen kurallara göre tek bir arabirim bildirimi oluşturmak için birleştirilir.Multiple partial interface declarations with the same name within an enclosing namespace or type declaration combine to form one interface declaration, following the rules specified in Partial types.

Değişken türü parametre listeleriVariant type parameter lists

Değişken türü parametre listeleri yalnızca arabirim ve temsilci türlerinde bulunabilir.Variant type parameter lists can only occur on interface and delegate types. Sıradan type_parameter_list s 'nin farkı, her tür parametresinde isteğe bağlı variance_annotation .The difference from ordinary type_parameter_list s is the optional variance_annotation on each type parameter.

variant_type_parameter_list
    : '<' variant_type_parameters '>'
    ;

variant_type_parameters
    : attributes? variance_annotation? type_parameter
    | variant_type_parameters ',' attributes? variance_annotation? type_parameter
    ;

variance_annotation
    : 'in'
    | 'out'
    ;

Varyans ek açıklaması ise out tür parametresi *covaryant _ olarak kabul edilir.If the variance annotation is out, the type parameter is said to be *covariant _. Varyans ek açıklaması ise in , tür parametresi değişken karşıtı olarak kabul edilir.If the variance annotation is in, the type parameter is said to be contravariant. Fark ek açıklaması yoksa, tür parametresi _ sabit * olarak kabul edilir.If there is no variance annotation, the type parameter is said to be _*invariant**.

ÖrnekteIn the example

interface C<out X, in Y, Z> 
{
  X M(Y y);
  Z P { get; set; }
}

X covaryant, değişken karşıtı Y ve Z sabit.X is covariant, Y is contravariant and Z is invariant.

Varyans güvenliğiVariance safety

Bir türün tür parametresi listesindeki fark ek açıklamaların oluşumu, türlerin tür bildiriminde gerçekleşebileceği yerleri kısıtlar.The occurrence of variance annotations in the type parameter list of a type restricts the places where types can occur within the type declaration.

Bir tür T , aşağıdakilerden biri olursa çıkış olarak güvenli değildir:A type T is output-unsafe if one of the following holds:

  • T değişken karşıtı bir tür parametresiT is a contravariant type parameter
  • T çıkış güvenli olmayan öğe türü olan bir dizi türüdürT is an array type with an output-unsafe element type
  • T , S<A1,...,Ak> aşağıdakilerden en az biri için olan genel bir türden oluşturulan bir arabirim veya temsilci türüdür S<X1,...,Xk> Ai :T is an interface or delegate type S<A1,...,Ak> constructed from a generic type S<X1,...,Xk> where for at least one Ai one of the following holds:
    • Xi birlikte değişken veya sabit, Ai çıkış ise güvenli değil.Xi is covariant or invariant and Ai is output-unsafe.
    • Xi değişken karşıtı veya değişmez ve Ai giriş açısından güvenlidir.Xi is contravariant or invariant and Ai is input-safe.

Aşağıdakilerden biri varsa, bir tür T giriş-güvenli değildir:A type T is input-unsafe if one of the following holds:

  • T bir birlikte değişken tür parametresidirT is a covariant type parameter
  • T giriş-güvenli olmayan öğe türü olan bir dizi türüdürT is an array type with an input-unsafe element type
  • T , S<A1,...,Ak> aşağıdakilerden en az biri için olan genel bir türden oluşturulan bir arabirim veya temsilci türüdür S<X1,...,Xk> Ai :T is an interface or delegate type S<A1,...,Ak> constructed from a generic type S<X1,...,Xk> where for at least one Ai one of the following holds:
    • Xi birlikte değişken veya sabit ve Ai giriş güvenli değil.Xi is covariant or invariant and Ai is input-unsafe.
    • Xi değişken karşıtı veya sabit, Ai çıkış ise güvenli değil.Xi is contravariant or invariant and Ai is output-unsafe.

Intuicanlı, çıkış konumunda güvenli olmayan bir türe izin verilmez ve giriş konumunda giriş güvensiz bir türe izin verilmez.Intuitively, an output-unsafe type is prohibited in an output position, and an input-unsafe type is prohibited in an input position.

Bir tür, çıkış güvenli değil,Çıkış güvenli olmayan bir türdür ve giriş güvensiz değilse _ Input-Safe* olur.A type is output-safe _ if it is not output-unsafe, and _ input-safe if it is not input-unsafe.

Varyans dönüştürmeVariance conversion

Fark ek açıklamalarının amacı, arabirim ve temsilci türlerine daha fazla bilgi vermek (ancak hala güvenli tür kullanımı) sağlamaktır.The purpose of variance annotations is to provide for more lenient (but still type safe) conversions to interface and delegate types. Bu uca örtük (örtük dönüştürmeler) ve açık dönüştürmeler (Açık dönüştürmeler) tanımları, aşağıdaki şekilde tanımlanan fark kullanımı kavramını kullanır:To this end the definitions of implicit (Implicit conversions) and explicit conversions (Explicit conversions) make use of the notion of variance-convertibility, which is defined as follows:

Bir tür T<A1,...,An> , bir T<B1,...,Bn> T arabirim ya da değişken tür parametreleriyle belirtilen bir temsilci türü ise T<X1,...,Xn> ve her bir değişken türü parametresi için Xi aşağıdaki tutmalar varsa, bir türe dönüştürülebilir:A type T<A1,...,An> is variance-convertible to a type T<B1,...,Bn> if T is either an interface or a delegate type declared with the variant type parameters T<X1,...,Xn>, and for each variant type parameter Xi one of the following holds:

  • Xibirlikte değişken ve öğesinden bir örtük başvuru ya da kimlik dönüştürmesi var Ai``BiXi is covariant and an implicit reference or identity conversion exists from Ai to Bi
  • Xideğişken karşıtı ve örtük bir başvuru ya da kimlik dönüştürme Bi``AiXi is contravariant and an implicit reference or identity conversion exists from Bi to Ai
  • Xisabit ve öğesinden bir kimlik dönüştürmesi var Ai``BiXi is invariant and an identity conversion exists from Ai to Bi

Temel arabirimlerBase interfaces

Arabirim, arabirimin Açık temel arabirimleri olarak adlandırılan sıfır veya daha fazla arabirim türünden kalıtımla alabilir.An interface can inherit from zero or more interface types, which are called the explicit base interfaces of the interface. Bir arabirimde bir veya daha fazla açık temel arabirim varsa, bu arabirimin bildiriminde, arabirim tanımlayıcısının ardından iki nokta üst üste ve temel arabirim türlerinin virgülle ayrılmış bir listesi gelir.When an interface has one or more explicit base interfaces, then in the declaration of that interface, the interface identifier is followed by a colon and a comma separated list of base interface types.

interface_base
    : ':' interface_type_list
    ;

Oluşturulmuş bir arabirim türü için, açık temel arabirimler genel tür bildiriminde açık temel arabirim bildirimleri alınarak, temel arabirim bildirimindeki her bir type_parameter için, oluşturulan türün karşılık gelen type_argument olarak oluşturulur.For a constructed interface type, the explicit base interfaces are formed by taking the explicit base interface declarations on the generic type declaration, and substituting, for each type_parameter in the base interface declaration, the corresponding type_argument of the constructed type.

Bir arabirimin açık temel arabirimleri en az arabirimin kendisi (Erişilebilirlik kısıtlamaları) olarak erişilebilir olmalıdır.The explicit base interfaces of an interface must be at least as accessible as the interface itself (Accessibility constraints). Örneğin, bir private internal arabirimin interface_base bir veya arabirimini belirtmek için derleme zamanı hatası vardır public .For example, it is a compile-time error to specify a private or internal interface in the interface_base of a public interface.

Bir arabirimin doğrudan veya dolaylı olarak kendisinden devraldığı derleme zamanı hatasıdır.It is a compile-time error for an interface to directly or indirectly inherit from itself.

Bir arabirimin temel arabirimleri , açık temel arabirimler ve bunların temel arabirimlerdir.The base interfaces of an interface are the explicit base interfaces and their base interfaces. Diğer bir deyişle, temel arabirimlerin kümesi açık temel arabirimlerin, kendi açık temel arabirimlerinin ve benzeri tüm geçişli kapamelerden oluşur.In other words, the set of base interfaces is the complete transitive closure of the explicit base interfaces, their explicit base interfaces, and so on. Arabirim, temel arabirimlerinin tüm üyelerini devralır.An interface inherits all members of its base interfaces. ÖrnekteIn the example

interface IControl
{
    void Paint();
}

interface ITextBox: IControl
{
    void SetText(string text);
}

interface IListBox: IControl
{
    void SetItems(string[] items);
}

interface IComboBox: ITextBox, IListBox {}

temel arabirimleri IComboBox IControl , ve ' dir ITextBox IListBox .the base interfaces of IComboBox are IControl, ITextBox, and IListBox.

Diğer bir deyişle, IComboBox Yukarıdaki arabirim üyeleri SetText ve ayrıca devralır SetItems Paint .In other words, the IComboBox interface above inherits members SetText and SetItems as well as Paint.

Bir arabirimin her temel arabirimi çıkış açısından güvenli (varyans güvenliği) olmalıdır.Every base interface of an interface must be output-safe (Variance safety). Arabirim uygulayan bir sınıf veya yapı, tüm arabirimin temel arabirimlerini de dolaylı olarak uygular.A class or struct that implements an interface also implicitly implements all of the interface's base interfaces.

Arabirim gövdesiInterface body

Bir arabirimin interface_body arabirimin üyelerini tanımlar.The interface_body of an interface defines the members of the interface.

interface_body
    : '{' interface_member_declaration* '}'
    ;

Arabirim üyeleriInterface members

Bir arabirimin üyeleri, taban arabirimlerinden devralınan ve arabirimin kendisi tarafından belirtilen üyelerin kendisidir.The members of an interface are the members inherited from the base interfaces and the members declared by the interface itself.

interface_member_declaration
    : interface_method_declaration
    | interface_property_declaration
    | interface_event_declaration
    | interface_indexer_declaration
    ;

Arabirim bildirimi, sıfır veya daha fazla üye bildirebilir.An interface declaration may declare zero or more members. Bir arabirimin üyeleri Yöntemler, özellikler, olaylar veya Dizin oluşturucular olmalıdır.The members of an interface must be methods, properties, events, or indexers. Arabirim, sabitler, alanlar, işleçler, örnek oluşturucular, Yıkıcılar veya türler içeremez ya da bir arabirim herhangi bir türde statik üyeler içerebilir.An interface cannot contain constants, fields, operators, instance constructors, destructors, or types, nor can an interface contain static members of any kind.

Tüm arabirim üyelerinin dolaylı olarak genel erişimi vardır.All interface members implicitly have public access. Arabirim üye bildirimlerinin herhangi bir değiştirici içermesi için derleme zamanı hatası vardır.It is a compile-time error for interface member declarations to include any modifiers. Özellikle, arabirimler üyeleri değiştiriciler,,,,,, abstract public protected internal private virtual override veya gibi bildirilemez static .In particular, interfaces members cannot be declared with the modifiers abstract, public, protected, internal, private, virtual, override, or static.

ÖrnekteThe example

public delegate void StringListEvent(IStringList sender);

public interface IStringList
{
    void Add(string s);
    int Count { get; }
    event StringListEvent Changed;
    string this[int index] { get; set; }
}

olası üye türlerinin her birini içeren bir arabirim bildirir: bir yöntem, özellik, olay ve Dizin Oluşturucu.declares an interface that contains one each of the possible kinds of members: A method, a property, an event, and an indexer.

İnterface_declaration yeni bir bildirim alanı (Bildirimler) oluşturur ve hemen interface_declaration tarafından bulunan interface_member_declaration, bu bildirim alanına yeni üyeler getirir.An interface_declaration creates a new declaration space (Declarations), and the interface_member_declaration s immediately contained by the interface_declaration introduce new members into this declaration space. İnterface_member_declaration s için aşağıdaki kurallar geçerlidir:The following rules apply to interface_member_declaration s:

  • Bir yöntemin adı, aynı arabirimde belirtilen tüm özelliklerin ve olayların adlarından farklı olmalıdır.The name of a method must differ from the names of all properties and events declared in the same interface. Ayrıca, bir yöntemin imzası (imzalar ve aşırı yükleme) aynı arabirimde belirtilen diğer tüm yöntemlerin imzalarından farklı olmalıdır ve aynı arabirimde belirtilen iki yöntem yalnızca ve ile farklı imzalara sahip olamaz ref out .In addition, the signature (Signatures and overloading) of a method must differ from the signatures of all other methods declared in the same interface, and two methods declared in the same interface may not have signatures that differ solely by ref and out.
  • Bir özelliğin veya olayın adı aynı arabirimde belirtilen diğer tüm üyelerin adlarından farklı olmalıdır.The name of a property or event must differ from the names of all other members declared in the same interface.
  • Bir dizin oluşturucunun imzası aynı arabirimde belirtilen diğer tüm dizin oluşturucularının imzalarından farklı olmalıdır.The signature of an indexer must differ from the signatures of all other indexers declared in the same interface.

Bir arabirimin devralınan üyeleri özellikle arabirimin bildirim alanının bir parçası değildir.The inherited members of an interface are specifically not part of the declaration space of the interface. Bu nedenle, bir arabirimin devralınan üye ile aynı ada veya imzaya sahip bir üyeyi bildirmesine izin verilir.Thus, an interface is allowed to declare a member with the same name or signature as an inherited member. Bu gerçekleştiğinde, türetilmiş arabirim üyesi temel arabirim üyesini gizleyecek şekilde söylenir.When this occurs, the derived interface member is said to hide the base interface member. Devralınan bir üyenin gizlenmesi bir hata sayılmaz, ancak derleyicinin bir uyarı vermesine neden olur.Hiding an inherited member is not considered an error, but it does cause the compiler to issue a warning. Uyarıyı bastırmak için, türetilen arabirim üyesinin bildirimi, new türetilen üyenin temel üyeyi gizlemek için tasarlanan bir değiştirici içermelidir.To suppress the warning, the declaration of the derived interface member must include a new modifier to indicate that the derived member is intended to hide the base member. Bu konu Devralma yoluyla gizlenerekdaha ayrıntılı bir şekilde ele alınmıştır.This topic is discussed further in Hiding through inheritance.

Bir new değiştirici devralınmış bir üyeyi gizlemez bir bildirime dahil edilir, bu etkiye bir uyarı verilir.If a new modifier is included in a declaration that doesn't hide an inherited member, a warning is issued to that effect. Bu uyarı, değiştirici kaldırılarak bastırılır new .This warning is suppressed by removing the new modifier.

Sınıftaki üyelerin, object herhangi bir arabirimin (arabirim üyesi) üyelerini değil, kesinlikle konuşmadığını unutmayın.Note that the members in class object are not, strictly speaking, members of any interface (Interface members). Ancak, sınıfındaki Üyeler object herhangi bir arabirim türünde (üye arama) üye arama yoluyla kullanılabilir.However, the members in class object are available via member lookup in any interface type (Member lookup).

Arabirim yöntemleriInterface methods

Arabirim yöntemleri interface_method_declaration s kullanılarak bildirilmiştir:Interface methods are declared using interface_method_declaration s:

interface_method_declaration
    : attributes? 'new'? return_type identifier type_parameter_list
      '(' formal_parameter_list? ')' type_parameter_constraints_clause* ';'
    ;

Bir arabirim yöntemi bildiriminin öznitelikleri, return_type, tanımlayıcısı ve formal_parameter_list , bir sınıftaki (Yöntemler) yöntem bildirimiyle aynı anlama sahiptir.The attributes, return_type, identifier, and formal_parameter_list of an interface method declaration have the same meaning as those of a method declaration in a class (Methods). Arabirim yöntemi bildiriminin bir yöntem gövdesi belirtmelerine izin verilmez ve bu nedenle bildirim, her zaman noktalı virgülle biter.An interface method declaration is not permitted to specify a method body, and the declaration therefore always ends with a semicolon.

Bir arabirim yönteminin her biçimsel parametre türü, giriş açısından güvenli (varyans güvenliği) olmalıdır ve dönüş türü void ya da çıkış açısından güvenli olmalıdır.Each formal parameter type of an interface method must be input-safe (Variance safety), and the return type must be either void or output-safe. Ayrıca, yöntemin herhangi bir tür parametresindeki her sınıf türü kısıtlaması, arabirim türü kısıtlaması ve tür parametresi kısıtlaması giriş açısından güvenli olmalıdır.Furthermore, each class type constraint, interface type constraint and type parameter constraint on any type parameter of the method must be input-safe.

Bu kurallar, arabirimin tüm değişkenle veya değişken karşıtı kullanımının tür açısından güvenli olmaya devam etmesini sağlamaktır.These rules ensure that any covariant or contravariant usage of the interface remains type-safe. Örneğin,For example,

interface I<out T> { void M<U>() where U : T; }

, T üzerinde tür parametresi kısıtlaması olarak kullanım U girişi güvenli olmadığından geçersizdir.is illegal because the usage of T as a type parameter constraint on U is not input-safe.

Bu kısıtlama yerinde değil, tür güvenliğini aşağıdaki şekilde ihlal etmek mümkün olacaktır:Were this restriction not in place it would be possible to violate type safety in the following manner:

class B {}
class D : B{}
class E : B {}
class C : I<D> { public void M<U>() {...} }
...
I<B> b = new C();
b.M<E>();

Bu aslında öğesine yapılan bir çağrıdır C.M<E> .This is actually a call to C.M<E>. Ancak bu çağrının E öğesinden D türemesini gerektirir, bu nedenle tür güvenliği burada çiğnenebilir.But that call requires that E derive from D, so type safety would be violated here.

Arabirim özellikleriInterface properties

Arabirim özellikleri interface_property_declaration s kullanılarak bildirilmiştir:Interface properties are declared using interface_property_declaration s:

interface_property_declaration
    : attributes? 'new'? type identifier '{' interface_accessors '}'
    ;

interface_accessors
    : attributes? 'get' ';'
    | attributes? 'set' ';'
    | attributes? 'get' ';' attributes? 'set' ';'
    | attributes? 'set' ';' attributes? 'get' ';'
    ;

Bir arabirim özelliği bildiriminin öznitelikleri, türü ve tanımlayıcısı , bir sınıftaki (Özellikler) bir özellik bildirimiyle aynı anlama sahiptir.The attributes, type, and identifier of an interface property declaration have the same meaning as those of a property declaration in a class (Properties).

Bir arabirim özelliği bildiriminin erişimcileri, bir sınıf özellik bildiriminin (erişimciler) erişimcilerine karşılık gelir, ancak erişimci gövdesi her zaman noktalı virgül olmalıdır.The accessors of an interface property declaration correspond to the accessors of a class property declaration (Accessors), except that the accessor body must always be a semicolon. Bu nedenle, erişimciler özelliğin okuma-yazma, salt okunurdur veya salt yazılır olduğunu gösterir.Thus, the accessors simply indicate whether the property is read-write, read-only, or write-only.

Bir get erişimcisi varsa bir arabirim özelliğinin türü çıkış güvende olmalıdır ve bir küme erişimcisi varsa giriş açısından güvenli olmalıdır.The type of an interface property must be output-safe if there is a get accessor, and must be input-safe if there is a set accessor.

Arabirim olaylarıInterface events

Arabirim olayları interface_event_declaration s kullanılarak bildirilmiştir:Interface events are declared using interface_event_declaration s:

interface_event_declaration
    : attributes? 'new'? 'event' type identifier ';'
    ;

Bir arabirim Olay bildiriminin öznitelikleri, türü ve tanımlayıcısı , bir sınıftaki olay bildirimiyle aynı anlama sahiptir (Olaylar).The attributes, type, and identifier of an interface event declaration have the same meaning as those of an event declaration in a class (Events).

Arabirim olayının türü giriş açısından güvenli olmalıdır.The type of an interface event must be input-safe.

Arabirim dizin oluşturucularInterface indexers

Arabirim dizin oluşturucular interface_indexer_declaration s kullanılarak bildirilmiştir:Interface indexers are declared using interface_indexer_declaration s:

interface_indexer_declaration
    : attributes? 'new'? type 'this' '[' formal_parameter_list ']' '{' interface_accessors '}'
    ;

Bir arabirim dizin oluşturucu bildiriminin öznitelikleri, türü ve formal_parameter_list , bir sınıftaki (Dizin oluşturucular) bir Indexer bildirimiyle aynı anlama sahiptir.The attributes, type, and formal_parameter_list of an interface indexer declaration have the same meaning as those of an indexer declaration in a class (Indexers).

Bir arabirim dizin oluşturucu bildiriminin erişimcileri, bir sınıf Dizin Oluşturucu bildirimi (Dizin oluşturucular) erişimcilerine karşılık gelir, ancak erişimci gövdesi her zaman noktalı virgül olmalıdır.The accessors of an interface indexer declaration correspond to the accessors of a class indexer declaration (Indexers), except that the accessor body must always be a semicolon. Bu nedenle, erişimciler dizin oluşturucunun salt okunurdur, salt okunurdur veya salt yazılır olduğunu gösterir.Thus, the accessors simply indicate whether the indexer is read-write, read-only, or write-only.

Bir arabirim dizin oluşturucunun tüm biçimsel parametre türleri giriş açısından güvenli olmalıdır.All the formal parameter types of an interface indexer must be input-safe . Ayrıca, herhangi bir out veya ref biçimsel parametre türü de çıkış açısından güvenli olmalıdır.In addition, any out or ref formal parameter types must also be output-safe. outTemel yürütme platformunun sınırlamasından dolayı, parametrelerin de giriş açısından güvenli olması gerektiğini unutmayın.Note that even out parameters are required to be input-safe, due to a limitation of the underlying execution platform.

Bir arabirim dizin oluşturucunun türü, bir get erişimcisi varsa çıkış güvende olmalıdır ve bir küme erişimcisi varsa giriş açısından güvenli olmalıdır.The type of an interface indexer must be output-safe if there is a get accessor, and must be input-safe if there is a set accessor.

Arabirim üye erişimiInterface member access

Arabirim üyelerine üye erişimi (üye erişimi) ve Dizin Oluşturucu erişimi (Dizin Oluşturucu erişimi) aracılığıyla erişilir I.M ve I[A] burada I bir arabirim türü, M Bu arabirim türünün bir yöntemi, özelliği ya da olayıdır ve bir A Dizin Oluşturucu bağımsız değişken listesidir.Interface members are accessed through member access (Member access) and indexer access (Indexer access) expressions of the form I.M and I[A], where I is an interface type, M is a method, property, or event of that interface type, and A is an indexer argument list.

Kesinlikle tek devralma olan arabirimler (devralma zincirindeki her arabirim tam olarak sıfır veya bir doğrudan temel arabirimine sahiptir), üye arama (üye arama), yöntem çağırma (Yöntem etkinleştirmeleri) ve Dizin Oluşturucu erişimi (Dizin Oluşturucu erişimi) kuralları, sınıflar ve yapılar için tamamen aynıdır: daha türetilmiş Üyeler aynı ad veya imzaya sahip daha az türetilmiş üyeleri gizler.For interfaces that are strictly single-inheritance (each interface in the inheritance chain has exactly zero or one direct base interface), the effects of the member lookup (Member lookup), method invocation (Method invocations), and indexer access (Indexer access) rules are exactly the same as for classes and structs: More derived members hide less derived members with the same name or signature. Ancak, birden fazla devralma arabirimi için, iki veya daha fazla ilişkisiz temel arabirim, aynı ad veya imzaya sahip Üyeler bildirse de gerçekleşebilir.However, for multiple-inheritance interfaces, ambiguities can occur when two or more unrelated base interfaces declare members with the same name or signature. Bu bölümde, bu durumların birkaç örneği gösterilmektedir.This section shows several examples of such situations. Her durumda, belirsizlikleri çözümlemek için açık yayınlar kullanılabilir.In all cases, explicit casts can be used to resolve the ambiguities.

ÖrnekteIn the example

interface IList
{
    int Count { get; set; }
}

interface ICounter
{
    void Count(int i);
}

interface IListCounter: IList, ICounter {}

class C
{
    void Test(IListCounter x) {
        x.Count(1);                  // Error
        x.Count = 1;                 // Error
        ((IList)x).Count = 1;        // Ok, invokes IList.Count.set
        ((ICounter)x).Count(1);      // Ok, invokes ICounter.Count
    }
}

içindeki üye araması (üye arama) belirsiz olduğundan, ilk iki deyim derleme zamanı hatalarına neden olur Count IListCounter .the first two statements cause compile-time errors because the member lookup (Member lookup) of Count in IListCounter is ambiguous. Örnekte gösterildiği gibi, belirsizlik x uygun temel arabirim türüne atama ile çözümlenir.As illustrated by the example, the ambiguity is resolved by casting x to the appropriate base interface type. Bu tür yayınlar hiçbir çalışma zamanı maliyetlerine sahip değildir; yalnızca derleme zamanında örneği daha az türetilmiş bir tür olarak görüntülemekden oluşur.Such casts have no run-time costs—they merely consist of viewing the instance as a less derived type at compile-time.

ÖrnekteIn the example

interface IInteger
{
    void Add(int i);
}

interface IDouble
{
    void Add(double d);
}

interface INumber: IInteger, IDouble {}

class C
{
    void Test(INumber n) {
        n.Add(1);                // Invokes IInteger.Add
        n.Add(1.0);              // Only IDouble.Add is applicable
        ((IInteger)n).Add(1);    // Only IInteger.Add is a candidate
        ((IDouble)n).Add(1);     // Only IDouble.Add is a candidate
    }
}

çağırma, n.Add(1) aşırı IInteger.Add yükleme çözümününaşırı yükleme çözümleme kurallarını uygulayarak seçilir.the invocation n.Add(1) selects IInteger.Add by applying the overload resolution rules of Overload resolution. Benzer şekilde, çağırma n.Add(1.0) seçilir IDouble.Add .Similarly the invocation n.Add(1.0) selects IDouble.Add. Açık yayınlar eklendiğinde yalnızca bir aday yöntemi vardır ve bu nedenle belirsizlik yoktur.When explicit casts are inserted, there is only one candidate method, and thus no ambiguity.

ÖrnekteIn the example

interface IBase
{
    void F(int i);
}

interface ILeft: IBase
{
    new void F(int i);
}

interface IRight: IBase
{
    void G();
}

interface IDerived: ILeft, IRight {}

class A
{
    void Test(IDerived d) {
        d.F(1);                 // Invokes ILeft.F
        ((IBase)d).F(1);        // Invokes IBase.F
        ((ILeft)d).F(1);        // Invokes ILeft.F
        ((IRight)d).F(1);       // Invokes IBase.F
    }
}

IBase.Füye, üye tarafından gizlenir ILeft.F .the IBase.F member is hidden by the ILeft.F member. Bu nedenle çağrı, tarafından d.F(1) ILeft.F IBase.F gelen erişim yolunda gizlenmese de görünür IRight .The invocation d.F(1) thus selects ILeft.F, even though IBase.F appears to not be hidden in the access path that leads through IRight.

Birden çok devralma arabirimindeki gizlemek için sezgisel kural yalnızca şu şekilde görünür: bir üye herhangi bir erişim yolunda gizliyse, tüm erişim yollarında gizlenir.The intuitive rule for hiding in multiple-inheritance interfaces is simply this: If a member is hidden in any access path, it is hidden in all access paths. IDerived' Den ' e erişim yolunun ILeft gizlenmesi için üye, IBase IBase.F erişim yolunda öğesinden öğesine de gizlenir IDerived IRight IBase .Because the access path from IDerived to ILeft to IBase hides IBase.F, the member is also hidden in the access path from IDerived to IRight to IBase.

Tam nitelikli arabirim üye adlarıFully qualified interface member names

Bir arabirim üyesine bazen tam adı verilir.An interface member is sometimes referred to by its fully qualified name. Bir arabirim üyesinin tam adı, üyenin bildirildiği arabirimin adından, ardından bir noktayla ve üyenin adından oluşur.The fully qualified name of an interface member consists of the name of the interface in which the member is declared, followed by a dot, followed by the name of the member. Üyenin tam adı üyenin bildirildiği arabirime başvurur.The fully qualified name of a member references the interface in which the member is declared. Örneğin, bildirimler verildiğindeFor example, given the declarations

interface IControl
{
    void Paint();
}

interface ITextBox: IControl
{
    void SetText(string text);
}

öğesinin tam adı Paint IControl.Paint ve tam adı ' SetText dir ITextBox.SetText .the fully qualified name of Paint is IControl.Paint and the fully qualified name of SetText is ITextBox.SetText.

Yukarıdaki örnekte, olarak başvurmak mümkün değildir Paint ITextBox.Paint .In the example above, it is not possible to refer to Paint as ITextBox.Paint.

Bir arabirim bir ad alanının parçasıysa, bir arabirim üyesinin tam adı ad alanı adını içerir.When an interface is part of a namespace, the fully qualified name of an interface member includes the namespace name. Örneğin:For example

namespace System
{
    public interface ICloneable
    {
        object Clone();
    }
}

Burada, metodun tam adı Clone System.ICloneable.Clone .Here, the fully qualified name of the Clone method is System.ICloneable.Clone.

Arabirim UygulamalarıInterface implementations

Arabirimler, sınıflar ve yapılar tarafından uygulanabilir.Interfaces may be implemented by classes and structs. Bir sınıfın veya yapının doğrudan bir arabirim uyguladığını göstermek için, arabirim tanımlayıcısı sınıf veya yapının temel sınıf listesine eklenir.To indicate that a class or struct directly implements an interface, the interface identifier is included in the base class list of the class or struct. Örnek:For example:

interface ICloneable
{
    object Clone();
}

interface IComparable
{
    int CompareTo(object other);
}

class ListEntry: ICloneable, IComparable
{
    public object Clone() {...}
    public int CompareTo(object other) {...}
}

Bir arabirimi doğrudan uygulayan bir sınıf veya yapı, tüm arabirimin temel arabirimlerini örtülü olarak doğrudan uygular.A class or struct that directly implements an interface also directly implements all of the interface's base interfaces implicitly. Bu, sınıf veya yapı, temel sınıf listesindeki tüm temel arabirimleri açıkça listemese bile geçerlidir.This is true even if the class or struct doesn't explicitly list all base interfaces in the base class list. Örnek:For example:

interface IControl
{
    void Paint();
}

interface ITextBox: IControl
{
    void SetText(string text);
}

class TextBox: ITextBox
{
    public void Paint() {...}
    public void SetText(string text) {...}
}

Burada, sınıfı TextBox hem hem de uygular IControl ITextBox .Here, class TextBox implements both IControl and ITextBox.

Bir sınıf C doğrudan bir arabirim uygularsa, C 'den türetilmiş tüm sınıflar da arabirimini örtülü olarak uygular.When a class C directly implements an interface, all classes derived from C also implement the interface implicitly. Bir sınıf bildiriminde belirtilen temel arabirimler, arabirim türleri (oluşturulmuş türler) ile oluşturulabilir.The base interfaces specified in a class declaration can be constructed interface types (Constructed types). Temel arabirim bir tür parametresi olamaz, ancak kapsamdaki tür parametreleri de içerebilir.A base interface cannot be a type parameter on its own, though it can involve the type parameters that are in scope. Aşağıdaki kod, bir sınıfın oluşturulmuş türleri nasıl uygulayabileceğinizi ve genişletdiğini gösterir:The following code illustrates how a class can implement and extend constructed types:

class C<U,V> {}

interface I1<V> {}

class D: C<string,int>, I1<string> {}

class E<T>: C<int,T>, I1<T> {}

Genel sınıf bildiriminin temel arabirimleri, uygulanan arabirimlerin benzersizlikbölümünde açıklanan benzersizlik kuralını karşılamalıdır.The base interfaces of a generic class declaration must satisfy the uniqueness rule described in Uniqueness of implemented interfaces.

Açık arabirim üye uygulamalarıExplicit interface member implementations

Arabirim uygulama amaçları doğrultusunda, bir sınıf veya yapı Açık arabirim üye uygulamaları bildirebilir.For purposes of implementing interfaces, a class or struct may declare explicit interface member implementations. Açık arabirim üyesi uygulama, tam arabirim üye adına başvuran bir yöntem, özellik, olay veya Dizin Oluşturucu bildirimidir.An explicit interface member implementation is a method, property, event, or indexer declaration that references a fully qualified interface member name. Örneğin:For example

interface IList<T>
{
    T[] GetElements();
}

interface IDictionary<K,V>
{
    V this[K key];
    void Add(K key, V value);
}

class List<T>: IList<T>, IDictionary<int,T>
{
    T[] IList<T>.GetElements() {...}
    T IDictionary<int,T>.this[int index] {...}
    void IDictionary<int,T>.Add(int index, T value) {...}
}

Burada IDictionary<int,T>.this ve IDictionary<int,T>.Add Açık arabirim üyesi uygulamalarıdır.Here IDictionary<int,T>.this and IDictionary<int,T>.Add are explicit interface member implementations.

Bazı durumlarda, bir arabirim üyesinin adı, uygulama sınıfı için uygun olmayabilir, bu durumda arabirim üyesi açık arabirim üye uygulaması kullanılarak uygulanabilir.In some cases, the name of an interface member may not be appropriate for the implementing class, in which case the interface member may be implemented using explicit interface member implementation. Örneğin, bir dosya soyutlama uygulayan bir sınıf büyük olasılıkla Close dosya kaynağını serbest bırakma etkisi olan bir üye işlevi uygulayabilir ve Dispose IDisposable Açık arabirim üye uygulamasını kullanarak arabirimin yöntemini uygular:A class implementing a file abstraction, for example, would likely implement a Close member function that has the effect of releasing the file resource, and implement the Dispose method of the IDisposable interface using explicit interface member implementation:

interface IDisposable
{
    void Dispose();
}

class MyFile: IDisposable
{
    void IDisposable.Dispose() {
        Close();
    }

    public void Close() {
        // Do what's necessary to close the file
        System.GC.SuppressFinalize(this);
    }
}

Bir yöntem çağırma, özellik erişimi veya Dizin Oluşturucu erişimi içindeki tam adı üzerinden açık arabirim üye uygulamasına erişmek mümkün değildir.It is not possible to access an explicit interface member implementation through its fully qualified name in a method invocation, property access, or indexer access. Açık arabirim üye uygulamasına yalnızca bir arabirim örneği aracılığıyla erişilebilir ve bu durumda yalnızca üye adı ile başvurulur.An explicit interface member implementation can only be accessed through an interface instance, and is in that case referenced simply by its member name.

Açık arabirim üye uygulamasının erişim değiştiricilerini içermesi için derleme zamanı hatası ve değiştiriciler,, veya dahil olmak üzere derleme zamanı hatası abstract virtual override static .It is a compile-time error for an explicit interface member implementation to include access modifiers, and it is a compile-time error to include the modifiers abstract, virtual, override, or static.

Açık arabirim üyesi uygulamalarının farklı erişilebilirlik özellikleri diğer üyelere göre daha vardır.Explicit interface member implementations have different accessibility characteristics than other members. Açık arabirim üyesi uygulamalarına hiçbir şekilde, bir yöntem çağrısında veya bir özellik erişiminde tam adı üzerinden erişilemeyeceğinden, bu özellikler bir özel anlamda özeldir.Because explicit interface member implementations are never accessible through their fully qualified name in a method invocation or a property access, they are in a sense private. Bununla birlikte, bir arabirim örneği üzerinden erişilebilecekleri için, bunlar da ortak bir fikir olabilir.However, since they can be accessed through an interface instance, they are in a sense also public.

Açık arabirim üyesi uygulamalar iki temel amaca hizmet eder:Explicit interface member implementations serve two primary purposes:

  • Açık arabirim üyesi uygulamalarına sınıf veya yapı örnekleri aracılığıyla erişilemediğinden, arabirim uygulamalarının bir sınıfın veya yapının ortak arabiriminden dışlanmalarını sağlar.Because explicit interface member implementations are not accessible through class or struct instances, they allow interface implementations to be excluded from the public interface of a class or struct. Bu, özellikle bir sınıf veya yapı, bu sınıf veya yapının tüketicisini ilgilenmeyen bir iç arabirim uygularsa yararlıdır.This is particularly useful when a class or struct implements an internal interface that is of no interest to a consumer of that class or struct.
  • Açık arabirim üye uygulamaları, aynı imzaya sahip arabirim üyelerinin belirsizine izin verir.Explicit interface member implementations allow disambiguation of interface members with the same signature. Açık arabirim üyesi uygulamalar olmadan, bir sınıf veya yapının aynı imzaya sahip olan ancak farklı dönüş türleriyle aynı imzaya sahip tüm arabirim üyeleri üzerinde herhangi bir uygulamaya sahip olması imkansız olacağı için, bir sınıf veya yapının aynı imza ve dönüş türüne sahip farklı arabirim üyesi uygulamalarına sahip olması imkansız olabilir.Without explicit interface member implementations it would be impossible for a class or struct to have different implementations of interface members with the same signature and return type, as would it be impossible for a class or struct to have any implementation at all of interface members with the same signature but with different return types.

Açık arabirim üyesi uygulamasının geçerli olması için, sınıf veya yapı birimi, tam adı, türü ve parametre türleri açık arabirim üye uygulamasıyla tam olarak eşleşen bir üyeyi içeren temel sınıf listesinde bir arabirim adı vermelidir.For an explicit interface member implementation to be valid, the class or struct must name an interface in its base class list that contains a member whose fully qualified name, type, and parameter types exactly match those of the explicit interface member implementation. Bu nedenle, aşağıdaki sınıftaThus, in the following class

class Shape: ICloneable
{
    object ICloneable.Clone() {...}
    int IComparable.CompareTo(object other) {...}    // invalid
}

öğesinin IComparable.CompareTo IComparable temel sınıf listesinde listelenmediği Shape ve temel arabirimi olmadığı için bir derleme zamanı hatası ile sonuçları bildirimi ICloneable .the declaration of IComparable.CompareTo results in a compile-time error because IComparable is not listed in the base class list of Shape and is not a base interface of ICloneable. Benzer şekilde, bildirimlerdeLikewise, in the declarations

class Shape: ICloneable
{
    object ICloneable.Clone() {...}
}

class Ellipse: Shape
{
    object ICloneable.Clone() {...}    // invalid
}

ICloneable.Clone' ın Ellipse ICloneable temel sınıf listesinde açıkça listelenmediğinden, içindeki bildirimi derleme zamanı hatası ile sonuçlanır Ellipse .the declaration of ICloneable.Clone in Ellipse results in a compile-time error because ICloneable is not explicitly listed in the base class list of Ellipse.

Bir arabirim üyesinin tam adı üyenin bildirildiği arabirime başvurmalıdır.The fully qualified name of an interface member must reference the interface in which the member was declared. Bu nedenle, bildirimlerdeThus, in the declarations

interface IControl
{
    void Paint();
}

interface ITextBox: IControl
{
    void SetText(string text);
}

class TextBox: ITextBox
{
    void IControl.Paint() {...}
    void ITextBox.SetText(string text) {...}
}

Açık arabirim üye uygulamasının Paint olarak yazılması gerekir IControl.Paint .the explicit interface member implementation of Paint must be written as IControl.Paint.

Uygulanan arabirimlerin benzersizliğiUniqueness of implemented interfaces

Genel tür bildirimiyle uygulanan arabirimler, tüm olası oluşturulmuş türler için benzersiz olmalıdır.The interfaces implemented by a generic type declaration must remain unique for all possible constructed types. Bu kural olmadan, belirli oluşturulmuş türler için çağrılacak doğru yöntemi belirleyeolanaksızdır.Without this rule, it would be impossible to determine the correct method to call for certain constructed types. Örneğin, bir genel sınıf bildiriminin şu şekilde yazılmasına izin verildiğini varsayalım:For example, suppose a generic class declaration were permitted to be written as follows:

interface I<T>
{
    void F();
}

class X<U,V>: I<U>, I<V>                    // Error: I<U> and I<V> conflict
{
    void I<U>.F() {...}
    void I<V>.F() {...}
}

Bu izin verildiğinde, hangi kodun çalıştırılacağını aşağıdaki örnekte belirleyeolanaksızdır:Were this permitted, it would be impossible to determine which code to execute in the following case:

I<int> x = new X<int,int>();
x.F();

Genel tür bildiriminin arabirim listesinin geçerli olup olmadığını anlamak için aşağıdaki adımlar gerçekleştirilir:To determine if the interface list of a generic type declaration is valid, the following steps are performed:

  • LGenel bir sınıfta, yapıda veya arabirim bildiriminde doğrudan belirtilen arabirimlerin listesi olmasına izin verin C .Let L be the list of interfaces directly specified in a generic class, struct, or interface declaration C.
  • LZaten içinde olan arabirimlerin herhangi bir temel arabirimine ekleyin L .Add to L any base interfaces of the interfaces already in L.
  • İçindeki tüm yinelemeleri kaldırın L .Remove any duplicates from L.
  • Bundan sonra oluşturulan herhangi bir derlenmiş tür varsa C , tür bağımsız değişkenleri öğesine eklendikten sonra, ' L de iki arabirimin aynı olmasına neden olur L , sonra bildirimi C geçersizdir.If any possible constructed type created from C would, after type arguments are substituted into L, cause two interfaces in L to be identical, then the declaration of C is invalid. Kısıtlama bildirimleri, tüm olası oluşturulmuş türler belirlenirken dikkate alınmıyor.Constraint declarations are not considered when determining all possible constructed types.

Yukarıdaki sınıf bildiriminde X , arabirim listesi L I<U> ve ' den oluşur I<V> .In the class declaration X above, the interface list L consists of I<U> and I<V>. Aynı türe sahip ve aynı türde olan oluşturulmuş bir tür, U V Bu iki arabirimin aynı türde olmasına neden olacağından bildirim geçersizdir.The declaration is invalid because any constructed type with U and V being the same type would cause these two interfaces to be identical types.

Farklı devralma düzeylerinde belirtilen arabirimlerin birleşmesini mümkün hale gelir:It is possible for interfaces specified at different inheritance levels to unify:

interface I<T>
{
    void F();
}

class Base<U>: I<U>
{
    void I<U>.F() {...}
}

class Derived<U,V>: Base<U>, I<V>    // Ok
{
    void I<V>.F() {...}
}

Bu kod, hem hem de uyguluyor olsa da geçerlidir Derived<U,V> I<U> I<V> .This code is valid even though Derived<U,V> implements both I<U> and I<V>. KodThe code

I<int> x = new Derived<int,int>();
x.F();

Derived Derived<int,int> etkin bir şekilde yeniden uyguladığından I<int> (arabirim yeniden uygulama) ' de yöntemini çağırır.invokes the method in Derived, since Derived<int,int> effectively re-implements I<int> (Interface re-implementation).

Genel yöntemlerin uygulanmasıImplementation of generic methods

Genel bir yöntem bir arabirim yöntemini örtük olarak uygularsa, her bir yöntem türü parametresi için verilen kısıtlamalar her iki bildirime de eşdeğer olmalıdır (herhangi bir arabirim türü parametre uygun tür bağımsız değişkenleriyle değiştirildikten sonra); burada yöntem türü parametreleri, soldan sağa doğru sıralı pozisyonlar tarafından tanımlanır.When a generic method implicitly implements an interface method, the constraints given for each method type parameter must be equivalent in both declarations (after any interface type parameters are replaced with the appropriate type arguments), where method type parameters are identified by ordinal positions, left to right.

Genel bir yöntem açıkça bir arabirim yöntemi uygularsa, uygulama yöntemi üzerinde hiçbir kısıtlamalara izin verilmez.When a generic method explicitly implements an interface method, however, no constraints are allowed on the implementing method. Bunun yerine, kısıtlamalar arabirim yönteminden devralınırInstead, the constraints are inherited from the interface method

interface I<A,B,C>
{
    void F<T>(T t) where T: A;
    void G<T>(T t) where T: B;
    void H<T>(T t) where T: C;
}

class C: I<object,C,string>
{
    public void F<T>(T t) {...}                    // Ok
    public void G<T>(T t) where T: C {...}         // Ok
    public void H<T>(T t) where T: string {...}    // Error
}

Yöntemi C.F<T> örtük olarak uygulanır I<object,C,string>.F<T> .The method C.F<T> implicitly implements I<object,C,string>.F<T>. Bu durumda, C.F<T> kısıtlama belirtmek için gerekli değildir (veya buna izin verilmez), T:object çünkü object tüm tür parametrelerinde örtük bir kısıtlamadır.In this case, C.F<T> is not required (nor permitted) to specify the constraint T:object since object is an implicit constraint on all type parameters. Yöntemi, arabirim C.G<T> I<object,C,string>.G<T> türü parametreleri karşılık gelen tür bağımsız değişkenleriyle değiştirildikten sonra, kısıtlama arayüzle eşleştiğinden, yöntem örtülü olarak uygular.The method C.G<T> implicitly implements I<object,C,string>.G<T> because the constraints match those in the interface, after the interface type parameters are replaced with the corresponding type arguments. C.H<T>Korumalı türler ( string Bu örnekte) kısıtlama olarak kullanılamadığından Yöntem kısıtlaması bir hatadır.The constraint for method C.H<T> is an error because sealed types (string in this case) cannot be used as constraints. Örtük arabirim yöntemi uygulamalarına ait kısıtlamaların eşleşmesi gerektiğinden kısıtlama bir hata da olur.Omitting the constraint would also be an error since constraints of implicit interface method implementations are required to match. Bu nedenle, örtülü olarak uygulamak olanaksızdır I<object,C,string>.H<T> .Thus, it is impossible to implicitly implement I<object,C,string>.H<T>. Bu arabirim yöntemi yalnızca açık bir arabirim üyesi uygulama kullanılarak uygulanabilir:This interface method can only be implemented using an explicit interface member implementation:

class C: I<object,C,string>
{
    ...

    public void H<U>(U u) where U: class {...}

    void I<object,C,string>.H<T>(T t) {
        string s = t;    // Ok
        H<T>(t);
    }
}

Bu örnekte, açık arabirim üye uygulama, kesinlikle daha zayıf kısıtlamalara sahip ortak bir yöntemi çağırır.In this example, the explicit interface member implementation invokes a public method having strictly weaker constraints. Öğesinden öğesine atama, t s T T:string Bu kısıtlama kaynak kodunda ifade edilemez olsa da, bir kısıtlamasını devraldığından geçerli olduğunu unutmayın.Note that the assignment from t to s is valid since T inherits a constraint of T:string, even though this constraint is not expressible in source code.

Arabirim eşlemeInterface mapping

Sınıf veya yapı birimi, sınıfın veya yapının temel sınıf listesinde listelenen arabirimlerin tüm üyelerine yönelik uygulamalar sağlamalıdır.A class or struct must provide implementations of all members of the interfaces that are listed in the base class list of the class or struct. Bir uygulama sınıfında veya yapıda arabirim üyelerinin uygulamalarını bulma işlemi arabirim eşleme olarak bilinir.The process of locating implementations of interface members in an implementing class or struct is known as interface mapping.

Bir sınıf veya yapı için arabirim eşlemesi C , öğesinin temel sınıf listesinde belirtilen her bir arabirimin her üyesi için bir uygulama konumlandırır C .Interface mapping for a class or struct C locates an implementation for each member of each interface specified in the base class list of C. Belirli bir arabirim üyesinin uygulanması, I.M burada I üyenin bildirildiği arabirim olduğu, M S C bir eşleşme bulunana kadar her bir ardışık taban sınıfı için ile başlayıp tekrarlanarak her bir sınıf veya yapının incelenmesiyle belirlenir C :The implementation of a particular interface member I.M, where I is the interface in which the member M is declared, is determined by examining each class or struct S, starting with C and repeating for each successive base class of C, until a match is located:

  • SVe ile eşleşen açık arabirim üye uygulamasının bir bildirimini içeriyorsa I M , bu üye uygulamasıdır I.M .If S contains a declaration of an explicit interface member implementation that matches I and M, then this member is the implementation of I.M.
  • Aksi takdirde, S ile eşleşen statik olmayan ortak üyenin bir bildirimini içeriyorsa M , bu üye uygulamasıdır I.M .Otherwise, if S contains a declaration of a non-static public member that matches M, then this member is the implementation of I.M. Birden fazla üye eşleşiyorsa, bu, öğesinin uygulanması belirtilmemiş olur I.M .If more than one member matches, it is unspecified which member is the implementation of I.M. Bu durum yalnızca S genel türde bildirildiği şekilde iki üyenin farklı imzaları olduğu, ancak tür bağımsız değişkenlerinin imzalarını özdeş hale oluşturduğu oluşturulmuş bir türse meydana gelebilir.This situation can only occur if S is a constructed type where the two members as declared in the generic type have different signatures, but the type arguments make their signatures identical.

Uygulamalar temel sınıf listesinde belirtilen tüm arabirimlerin tüm üyeleri için bulunamıyorsa, derleme zamanı hatası oluşur C .A compile-time error occurs if implementations cannot be located for all members of all interfaces specified in the base class list of C. Bir arabirimin üyelerinin temel arabirimlerden devralınan üyeleri olduğunu unutmayın.Note that the members of an interface include those members that are inherited from base interfaces.

Arabirim eşleme amaçları doğrultusunda, bir sınıf üyesi şu A durumlarda bir arabirim üyesiyle eşleşir B :For purposes of interface mapping, a class member A matches an interface member B when:

  • A ve B metodlardır ve ad, tür ve biçimsel parametre listeleri A B aynıdır.A and B are methods, and the name, type, and formal parameter lists of A and B are identical.
  • A , ve ' B nin adı ve türü aynıdır ve A B A aynı erişimcilere sahiptir B ( A açık bir arabirim üyesi uygulama değilse ek erişimcilere izin verilir).A and B are properties, the name and type of A and B are identical, and A has the same accessors as B (A is permitted to have additional accessors if it is not an explicit interface member implementation).
  • A ve B olayları ve adı ve türü A B özdeş.A and B are events, and the name and type of A and B are identical.
  • A ve B Dizin oluşturucular, tür ve biçimsel parametre listeleri ve aynıdır A B ve A aynı erişimcilere sahiptir B ( A Açık arabirim üyesi uygulama değilse ek erişimcilere izin verilir).A and B are indexers, the type and formal parameter lists of A and B are identical, and A has the same accessors as B (A is permitted to have additional accessors if it is not an explicit interface member implementation).

Arabirim eşleme algoritmasının önemli etkileri şunlardır:Notable implications of the interface mapping algorithm are:

  • Açık arabirim üyesi uygulamalar, bir arabirim üyesini uygulayan sınıf veya yapı üyesini belirlerken aynı sınıftaki veya yapıdaki diğer üyelere göre önceliklidir.Explicit interface member implementations take precedence over other members in the same class or struct when determining the class or struct member that implements an interface member.
  • Hiçbir ortak olmayan veya statik üye arabirim eşlemesine katılmaz.Neither non-public nor static members participate in interface mapping.

ÖrnekteIn the example

interface ICloneable
{
    object Clone();
}

class C: ICloneable
{
    object ICloneable.Clone() {...}
    public object Clone() {...}
}

ICloneable.Cloneöğesi, C Clone ICloneable Açık arabirim üye uygulamaları diğer üyelere göre öncelikli olduğundan, ' nin uygulamasına uygulanması olur.the ICloneable.Clone member of C becomes the implementation of Clone in ICloneable because explicit interface member implementations take precedence over other members.

Bir sınıf veya yapı birimi, aynı ada, türe ve parametre türlerine sahip bir üyeyi içeren iki veya daha fazla arabirim uygularsa, bu arabirim üyelerinin her birini tek bir sınıf veya yapı üyesi üzerinde eşlemek mümkündür.If a class or struct implements two or more interfaces containing a member with the same name, type, and parameter types, it is possible to map each of those interface members onto a single class or struct member. Örneğin:For example

interface IControl
{
    void Paint();
}

interface IForm
{
    void Paint();
}

class Page: IControl, IForm
{
    public void Paint() {...}
}

Burada, Paint IControl ve yöntemleri IForm Paint içindeki yöntemiyle eşleştirilir Page .Here, the Paint methods of both IControl and IForm are mapped onto the Paint method in Page. İki yöntem için ayrı açık arabirim üyesi uygulamalarına de sahip olmak mümkündür.It is of course also possible to have separate explicit interface member implementations for the two methods.

Bir sınıf veya yapı, gizli Üyeler içeren bir arabirim uygularsa, bazı üyelerin açık arabirim üye uygulamaları aracılığıyla uygulanması gerekir.If a class or struct implements an interface that contains hidden members, then some members must necessarily be implemented through explicit interface member implementations. Örneğin:For example

interface IBase
{
    int P { get; }
}

interface IDerived: IBase
{
    new int P();
}

Bu arabirimin uygulanması için en az bir açık arabirim üyesi uygulamanız gerekir ve aşağıdaki biçimlerden birini alırAn implementation of this interface would require at least one explicit interface member implementation, and would take one of the following forms

class C: IDerived
{
    int IBase.P { get {...} }
    int IDerived.P() {...}
}

class C: IDerived
{
    public int P { get {...} }
    int IDerived.P() {...}
}

class C: IDerived
{
    int IBase.P { get {...} }
    public int P() {...}
}

Bir sınıf, aynı temel arabirime sahip birden çok arabirim uygularsa, temel arabirimin yalnızca bir uygulama olabilir.When a class implements multiple interfaces that have the same base interface, there can be only one implementation of the base interface. ÖrnekteIn the example

interface IControl
{
    void Paint();
}

interface ITextBox: IControl
{
    void SetText(string text);
}

interface IListBox: IControl
{
    void SetItems(string[] items);
}

class ComboBox: IControl, ITextBox, IListBox
{
    void IControl.Paint() {...}
    void ITextBox.SetText(string text) {...}
    void IListBox.SetItems(string[] items) {...}
}

IControltemel sınıf listesinde, IControl devralınan ITextBox ve devralınan ' de adlandırılmış ayrı uygulamalar olması mümkün değildir IControl IListBox .it is not possible to have separate implementations for the IControl named in the base class list, the IControl inherited by ITextBox, and the IControl inherited by IListBox. Aslında, bu arabirimler için ayrı bir kimlik kavramı yoktur.Indeed, there is no notion of a separate identity for these interfaces. Bunun yerine, ve uygulamalarının ITextBox IListBox aynı uygulamasını paylaşır IControl ve ComboBox yalnızca üç Arabirim (,, ve) uygulamak için kabul edilir IControl ITextBox IListBox .Rather, the implementations of ITextBox and IListBox share the same implementation of IControl, and ComboBox is simply considered to implement three interfaces, IControl, ITextBox, and IListBox.

Bir temel sınıfın üyeleri arabirim eşlemesine katılır.The members of a base class participate in interface mapping. ÖrnekteIn the example

interface Interface1
{
    void F();
}

class Class1
{
    public void F() {}
    public void G() {}
}

class Class2: Class1, Interface1
{
    new public void G() {}
}

içindeki yöntemi, uygulamasının uygulamasında F Class1 kullanılır Class2 Interface1 .the method F in Class1 is used in Class2's implementation of Interface1.

Arabirim uygulama devralmaInterface implementation inheritance

Bir sınıf, kendi temel sınıfları tarafından sunulan tüm arabirim uygulamalarını devralır.A class inherits all interface implementations provided by its base classes.

Bir arabirimi açıkça yeniden uygulamadan , türetilmiş bir sınıf herhangi bir şekilde kendi temel sınıflarından devraladığı arabirim eşlemelerini değiştiremez.Without explicitly re-implementing an interface, a derived class cannot in any way alter the interface mappings it inherits from its base classes. Örneğin, bildirimlerdeFor example, in the declarations

interface IControl
{
    void Paint();
}

class Control: IControl
{
    public void Paint() {...}
}

class TextBox: Control
{
    new public void Paint() {...}
}

Paintiçindeki yöntemi TextBox Paint içindeki yöntemini gizler Control , ancak üzerine eşlemesini değiştirmez Control.Paint IControl.Paint ve Paint sınıf örnekleri ve arabirim örnekleri aracılığıyla yapılan çağrılar aşağıdaki etkilere sahip olacaktırthe Paint method in TextBox hides the Paint method in Control, but it does not alter the mapping of Control.Paint onto IControl.Paint, and calls to Paint through class instances and interface instances will have the following effects

Control c = new Control();
TextBox t = new TextBox();
IControl ic = c;
IControl it = t;
c.Paint();            // invokes Control.Paint();
t.Paint();            // invokes TextBox.Paint();
ic.Paint();           // invokes Control.Paint();
it.Paint();           // invokes Control.Paint();

Ancak, bir arabirim yöntemi bir sınıftaki sanal bir yönteme eşlendiğinde, türetilmiş sınıfların sanal yöntemi geçersiz kılmasını ve arabirimin uygulamasını değiştirmesini mümkün hale gelir.However, when an interface method is mapped onto a virtual method in a class, it is possible for derived classes to override the virtual method and alter the implementation of the interface. Örneğin, yukarıdaki bildirimleri yeniden yazmaFor example, rewriting the declarations above to

interface IControl
{
    void Paint();
}

class Control: IControl
{
    public virtual void Paint() {...}
}

class TextBox: Control
{
    public override void Paint() {...}
}

aşağıdaki efektler artık gözlemlenecekthe following effects will now be observed

Control c = new Control();
TextBox t = new TextBox();
IControl ic = c;
IControl it = t;
c.Paint();            // invokes Control.Paint();
t.Paint();            // invokes TextBox.Paint();
ic.Paint();           // invokes Control.Paint();
it.Paint();           // invokes TextBox.Paint();

Açık arabirim üyesi uygulamalar sanal olarak bildirilemediğinden açık arabirim üyesi uygulamasını geçersiz kılmak mümkün değildir.Since explicit interface member implementations cannot be declared virtual, it is not possible to override an explicit interface member implementation. Ancak, bir açık arabirim üye uygulamasının başka bir yöntemi çağırması için ve diğer yöntem, türetilmiş sınıfların bunu geçersiz kılmasına izin vermek için sanal olarak bildirilebilecek kadar geçerlidir.However, it is perfectly valid for an explicit interface member implementation to call another method, and that other method can be declared virtual to allow derived classes to override it. Örneğin:For example

interface IControl
{
    void Paint();
}

class Control: IControl
{
    void IControl.Paint() { PaintControl(); }
    protected virtual void PaintControl() {...}
}

class TextBox: Control
{
    protected override void PaintControl() {...}
}

Burada, öğesinden türetilmiş sınıflar Control IControl.Paint yöntemini geçersiz kılarak uygulamasını özelleştirecek PaintControl .Here, classes derived from Control can specialize the implementation of IControl.Paint by overriding the PaintControl method.

Arabirim yeniden uygulamaInterface re-implementation

Arabirim uygulamasını devralan bir sınıf, arabirimi temel sınıf listesine dahil ederek yeniden uygulamaya izin verilir.A class that inherits an interface implementation is permitted to re-implement the interface by including it in the base class list.

Bir arabirimin yeniden uygulanması, bir arabirimin ilk uygulamasıyla tam olarak aynı arabirim eşleme kurallarını izler.A re-implementation of an interface follows exactly the same interface mapping rules as an initial implementation of an interface. Bu nedenle, devralınan arabirim eşlemesinin, arabirimin yeniden uygulanması için belirlenen arabirim eşlemesi üzerinde hiçbir etkisi yoktur.Thus, the inherited interface mapping has no effect whatsoever on the interface mapping established for the re-implementation of the interface. Örneğin, bildirimlerdeFor example, in the declarations

interface IControl
{
    void Paint();
}

class Control: IControl
{
    void IControl.Paint() {...}
}

class MyControl: Control, IControl
{
    public void Paint() {}
}

' den ' Control ye eşlenen olgu, ' IControl.Paint Control.IControl.Paint de ' de bulunan yeniden uygulamayı etkilemez MyControl IControl.Paint MyControl.Paint .the fact that Control maps IControl.Paint onto Control.IControl.Paint doesn't affect the re-implementation in MyControl, which maps IControl.Paint onto MyControl.Paint.

Devralınan ortak üye bildirimleri ve devralınmış açık arabirim üye bildirimleri, yeniden uygulanan arabirimler için arabirim eşleme işlemine katılır.Inherited public member declarations and inherited explicit interface member declarations participate in the interface mapping process for re-implemented interfaces. Örneğin:For example

interface IMethods
{
    void F();
    void G();
    void H();
    void I();
}

class Base: IMethods
{
    void IMethods.F() {}
    void IMethods.G() {}
    public void H() {}
    public void I() {}
}

class Derived: Base, IMethods
{
    public void F() {}
    void IMethods.H() {}
}

Burada, ' ın uygulanması IMethods Derived arabirim yöntemlerini Derived.F ,, Base.IMethods.G , ve üzerine eşler Derived.IMethods.H Base.I .Here, the implementation of IMethods in Derived maps the interface methods onto Derived.F, Base.IMethods.G, Derived.IMethods.H, and Base.I.

Bir sınıf bir arabirim uygularsa, örtülü olarak bu arabirimin tüm temel arabirimlerini de uygular.When a class implements an interface, it implicitly also implements all of that interface's base interfaces. Benzer şekilde, bir arabirimin yeniden uygulanması, tüm arabirimin temel arabirimlerinin de örtük bir şekilde yeniden uygulanmasını de ister.Likewise, a re-implementation of an interface is also implicitly a re-implementation of all of the interface's base interfaces. Örneğin:For example

interface IBase
{
    void F();
}

interface IDerived: IBase
{
    void G();
}

class C: IDerived
{
    void IBase.F() {...}
    void IDerived.G() {...}
}

class D: C, IDerived
{
    public void F() {...}
    public void G() {...}
}

Burada, ' nin yeniden uygulanması IDerived IBase , ' nin üzerine eşleme de yeniden IBase.F uygulanır D.F .Here, the re-implementation of IDerived also re-implements IBase, mapping IBase.F onto D.F.

Soyut sınıflar ve arabirimlerAbstract classes and interfaces

Soyut olmayan bir sınıf gibi soyut bir sınıf, sınıfın temel sınıf listesinde listelenen arabirimlerin tüm üyelerinin uygulamalarını sağlamalıdır.Like a non-abstract class, an abstract class must provide implementations of all members of the interfaces that are listed in the base class list of the class. Ancak soyut bir sınıfın, Arabirim yöntemlerinin soyut yöntemlerle eşlenme izni vardır.However, an abstract class is permitted to map interface methods onto abstract methods. Örneğin:For example

interface IMethods
{
    void F();
    void G();
}

abstract class C: IMethods
{
    public abstract void F();
    public abstract void G();
}

Burada, IMethods haritalar F ve ' G den türetilen soyut olmayan sınıflarda geçersiz kılınabilmesi gereken soyut yöntemler üzerinde uygulama C .Here, the implementation of IMethods maps F and G onto abstract methods, which must be overridden in non-abstract classes that derive from C.

Açık arabirim üye uygulamalarının soyut olamayacağını, ancak açık arabirim üye uygulamalarının soyut yöntemleri çağırmasına izin verildiğini unutmayın.Note that explicit interface member implementations cannot be abstract, but explicit interface member implementations are of course permitted to call abstract methods. Örneğin:For example

interface IMethods
{
    void F();
    void G();
}

abstract class C: IMethods
{
    void IMethods.F() { FF(); }
    void IMethods.G() { GG(); }
    protected abstract void FF();
    protected abstract void GG();
}

Burada, öğesinden türetilen soyut olmayan sınıfların C FF GG , ve fiili uygulamasının sağlanması gerekir IMethods .Here, non-abstract classes that derive from C would be required to override FF and GG, thus providing the actual implementation of IMethods.