昨天,当使用某些Entity Framework东西时,我尝试编写它,并收到错误“ ObjectContext不是成员”等。
context.ObjectContext.Refresh(RefreshMode.StoreWins, myObject);
现在,上下文继承了此处记录的DbContext对象:http : //msdn.microsoft.com/zh-cn/library/system.data.entity.dbcontext( v=vs.103) .aspx
这是“ is a”类型的正常继承-我的上下文对象是DbContext对象。DbContext类实现了IObjectContextAdapter接口,因此我希望上面的代码可以工作-接口声明的成员函数必须在DbContext类中实现,否则,我希望它在编译时失败,并带有“您必须实现接口”错误。但是,当我们查看生成的类定义时,它不存在!
最终,我实现了这样的调用,编译器接受了该调用。
((IObjectContextAdapter)context).ObjectContext.Refresh(RefreshMode.StoreWins, myObject);
当以下代码相同且可以正常工作时,谁能解释为什么我必须这样做?
interface IMyInterface {
int MyInterfaceMemberFunction();
}
public class MyObjectClass : IMyInterface {
public int MyInterfaceMemberFunction() { return 17; }
}
public class MyTestClass {
public int MyTestFunction() {
MyObjectClass m = new MyObjectClass();
return m.MyInterfaceMemberFunction(); //error here for EF context
}
}
这是因为该ObjectContext
属性是显式实现的。要使用您的示例进行演示:
interface IMyInterface {
int MyInterfaceMemberFunction();
}
public class MyObjectClass : IMyInterface {
// this line changed:
int IMyInterface.MyInterfaceMemberFunction() { return 17; }
}
public class MyTestClass {
public int MyTestFunction() {
MyObjectClass m = new MyObjectClass();
//return m.MyInterfaceMemberFunction(); //error here
return ((IMyInterface)m).MyInterfaceMemberFunction(); //this works
}
}
如果您有两个接口用相同的名称定义不同的成员,则必须明确实现。如果您希望正常使用类的人不会注意到它们,它也可以用于隐藏某些接口成员。例如,List<T>
器具IList
,但明确工具IList.Add(object)
,让你不小心尝试什么,但添加T
到List<T>
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句