2016-03-16 72 views
1

我有一個接口:爲什麼我需要在C#顯式實現中將「this」強制轉換爲接口類型?

public interface Profile 
{ 
    string Name { get; } 
    string Alias { get; set; } 
} 

實現Profile所有的對象都有一個NameAlias,但一些限制Alias,使得它總是一樣Name。適用此限制的功能才能實現Alias這樣的:

string Profile.Alias 
{ 
    get 
    { 
     return ((Profile)this).Name; 
    } 
    set { } 
} 

由於顯式接口實現的範圍內this只能有可能是Profile型的,我們知道這是通過Profile接口,而不是的訪問包含的類或其實現的任何其他接口,爲什麼需要演員?

使用return this.Name;對該錯誤,吸氣實施效果:

Type `ConcreteProfile' does not contain a definition for `Name' and no extension method `Name' of type `ConcreteProfile' could be found (are you missing a using directive or an assembly reference?) 
+0

爲什麼不簡單地使用字符串別名=>名稱(c#6)或字符串別名{get {return Name;}}? – Boo

+0

@Boo:因爲它需要實現具有setter的接口。就我個人而言,我會讓setter拋出一個異常,而不是忽略通話...或重新設計界面。 –

回答

4

Since this within the context of an explicit interface implementation can only possibly be of type Profile

這是不正確的。您正在執行ConcreteProfile課程中的Profile.Alias。在這種情況下,this指的是ConcreteProfile實例,可用於訪問ConcreteProfile實例的任何成員。

例如,ConcreteProfile類可以包含另一個Name屬性,該屬性不是Profile.Name。在這種情況下,this.Name將引用該屬性。

既然您想訪問Profile.Name,您必須將this投射到Profile

3

Since this within the context of an explicit interface implementation can only possibly be of type Profile and we know it was accessed through the Profile interface rather than that of the containing class or any other interface it implements, why is the cast required?

因爲它使用顯式接口實現。這只是顯式接口實現的一部分 - 它是如何實現消除其他含糊不清的調用的目的的一部分。從C#5規範,第13.4.1:

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. An explicit interface member implementation can only be accessed through an interface instance, and is in that case referenced simply by its member name.

...

Explicit interface member implementations serve two primary purposes:

  • 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. 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.
  • Explicit interface member implementations allow disambiguation of interface members with the same signature. 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.
相關問題