为什么我不能直接调用DbContext.ObjectContext?

Lar*_*rry 2 c# entity-framework

为什么我不能DbContext.ObjectContext直接打电话?我可以做这个((IObjectContextAdapter)context).ObjectContext

我认为内部机制是这样的接口的隐式实现

class Program 
{ 
    static void Main(string[] args) 
    { 
        TestClass t = new TestClass(); 
        ((TestInterface)t).TestMethod(); 
        // I can't call t.TestMethod()
        Console.ReadKey(); 
    } 
} 

public interface TestInterface 
{ 
    void TestMethod(); 
} 

public class TestClass : TestInterface 
{ 
    void TestInterface.TestMethod() 
    { 
        Console.WriteLine("abcdefg"); 
    } 
}
Run Code Online (Sandbox Code Playgroud)

我遇到此问题之前是IEnumerable<T>继承IEnumerable,它具有通用版本IEnumerator<T> GetEnumerator()和非泛型版本IEnumerator GetEnumerator(),但您只能调用通用版本而不是非通用版本.因为非泛型的不是类型安全的,作者想隐藏它.

但是DbContext类的原因是什么?

Tyl*_*Lee 5

因为ObjectContext是在DbContext类中显式实现的(如MSDN - DbContext所示),所以必须将对象显式转换为接口以调用Property.

"当一个成员被显式实现时,它不能通过类实例访问,而只能通过接口的实例访问." - MSDN - 显式接口实现教程

希望这可以帮助!