部分类中的接口实现问题

我有一个关于L2S,Autogenerated DataContext和Partial Classes的使用问题的问题。 我已经抽象了我的datacontext,并且对于我使用的每个表,我正在实现一个带接口的类。 在下面的代码中,您可以看到我有接口和两个分部类。 第一个类就是确保自动生成的datacontext中的类具有接口。 另一个自动生成的类确保实现Interface的方法。

namespace PartialProject.objects { public interface Interface { Interface Instance { get; } } //To make sure the autogenerated code inherits Interface public partial class Class : Interface { } //This is autogenerated public partial class Class { public Class Instance { get { return this.Instance; } } } } 

现在我的问题是在自动生成的类中实现的方法会出现以下错误: – >属性’Instance’无法实现接口’PartialProject.objects.Interface’的属性。 类型应为’PartialProjects.objects.Interface’。 < –

知道如何解决这个错误吗? 请记住,我无法在自动生成的代码中编辑任何内容。

提前致谢!

您可以通过显式实现接口来解决此问题:

 namespace PartialProject.objects { public interface Interface { Interface Instance { get; } } //To make sure the autogenerated code inherits Interface public partial class Class : Interface { Interface Interface.Instance { get { return Instance; } } } //This is autogenerated public partial class Class { public Class Instance { get { return this.Instance; } } } } 

返回类型在C#中不协变。 由于您无法更改自动生成的代码,因此我看到的唯一解决方案是更改界面:

 public interface Interface { T Instance { get; } } 

并相应地更改您的部分课程:

 public partial class Class : Interface { }