2014-03-05 71 views
4

問題在短期: 公共類的DbContext:IDisposable接口,IObjectContextAdapter接口如何暴露實現類中不存在的公共屬性/方法?

的DbContext實現IObjectContextAdapter。 IObjectContextAdapter有一個單一的財產,

public interface IObjectContextAdapter 
{ 
    // Summary: 
    //  Gets the object context. 
    ObjectContext ObjectContext { get; } 
} 

但是,我無法找到的DbContext這個屬性;它在元數據代碼中並不存在。只有訪問它的方法是將DbContext轉換爲IObjectContextAdapter。

我不明白 - 我會一直認爲,一個界面的公共屬性是由實現類暴露無論是投在接口與否。我覺得我失去了一些東西在這裏大...

+0

一個實現類必須實現接口的所有成員,否則它不是實現者。 – Jodrell

+0

Doh,我剛剛找到答案 - 顯式接口實現私有屬性只暴露在接口?每天學習新東西! –

回答

4

這意味着,DbContext實施了財產明確,就像這樣:

public class DbContext : IObjectContextAdapter 
{ 
    ObjectContext IObjectContextAdapter.ObjectContext { get { ... }} 
} 

如果成員被顯式實現,實例將不得不被鑄造到它的接口以便被訪問。

技術是用於實現兩個部件具有相同簽名通常是有用的。例如,實施IEnumerable<T>的時候,你必須實現兩個成員:

  • IEnumerator GetEnumeratorIEnumerable
  • IEnumerator<T> GetEnumeratorIEnumerable<T>

他們中的一個將已經被明確實施:

public class X : IEnumerable<int> 
{ 
    public IEnumerator<int> GetEnumerator() 
    { 
     throw new NotImplementedException(); 
    } 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return GetEnumerator(); 
    } 
} 

Some cla在.NET框架中使用它可以將其用於隱藏或者阻止某些成員的使用。 ConcurrentQueue<T>鼓勵的IProducerConsumerCollection.TryAdd使用和鼓勵ConcurrentQueue<T>.Enqueue使用來代替。

參見:MSDN Explicit Interface Implementation

1

你們看到的是顯式接口implmentation,見下文

interface IExplicit 
{ 
    void Explicit(); 
} 

class Something : IExplicit 
{ 
    void IExplicit.Explicit() 
    { 
    } 
} 

這樣,我們就可以實例化一個new Something(),但訪問IExplicit實現我們投的類型。

var something = new Something(); 

// Compile time error. 
something.Explicit(); 

// But we can do. 
((IExplicit)something).Explicit();