2

为什么不能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"); 
    } 
}

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

但是DbContext类的原因是什么?

4

3 回答 3

5

Because ObjectContext is implemented explicitly in the DbContext class (as shown on the MSDN - DbContext) you have to explicitly cast your object to the Interface to call the Property.

" When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface. " - MSDN - Explicit Interface Implementation Tutorial

Hope this helps!

于 2012-10-26T15:15:13.513 回答
1

我怀疑因为ObjectContext已被弃用而支持DbContext. DbContext是一个比ObjectContext.

于 2012-10-26T15:08:44.443 回答
0

如果您检查Codeplex上可用的 DbContext 类的源代码,则会显式实现 ObjectContext 属性。这是源代码中的一段代码(我已删除评论):

ObjectContext IObjectContextAdapter.ObjectContext
        {
            get
            {
                InternalContext.ForceOSpaceLoadingForKnownEntityTypes();
                return InternalContext.ObjectContext;
            }
        }

这就是为什么您不能使用 DbContext 对象调用属性 O​​bjectContext 而不将其转换为 IObjectContextAdapter 类型的原因。

于 2012-10-26T15:33:27.087 回答