2014-03-05 69 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();