【问题标题】:Can one implement an interface property on an Entity Object interface?可以在实体对象接口上实现接口属性吗?
【发布时间】:2011-04-17 13:39:25
【问题描述】:

我正在使用实体框架,并为租赁交易创建了一个接口:

public interface ILeaseTransaction
{
    int ID { get; }
    DateTime Date { get; }
    decimal Amount { get; }
}

然后为了在实体对象上实现接口,我创建了一个空的部分类:

public partial class Type1LeaseTransaction : ILeaseTransaction
{

}

这很好用,但是交易也可以有零个或一个也是实体对象的 Void。我尝试按如下方式实现 Void:

public interface ILeaseTransactionVoid
{
    int TransactionID { get; }
    DateTime Date { get; }
    int TypeID { get; }
}

还有空的部分类...:

public partial class Type1LeaseTransactionVoid : ILeaseTransactionVoid
{

}

我遇到的问题是当我尝试将ILeaseTransactionVoid 作为属性添加到LeaseTransaction 接口时:

public interface ILeaseTransaction
{
    int ID { get; }
    DateTime Date { get; }
    decimal Amount { get; }
    ILeaseTransactionVoid Void { get; } // This throws an error
}

当我尝试构建时,我收到以下错误:

“DomainModel.Models.Type1LeaseTransaction”没有实现接口成员“DomainModel.Abstract.ILeaseTransaction.Void”。 “DomainModel.Models.Type1LeaseTransaction.Void”无法实现“DomainModel.Abstract.ILeaseTransaction.Void” 因为它没有匹配的返回类型'DomainModel.Abstract.ILeaseTransactionVoid'。

我猜这个错误是有道理的,因为返回类型不是接口本身,即使它实现了接口。我对这一切都很陌生,所以我现在完全迷失了。

我有什么办法可以在ILeaseTransaction上实现嵌套接口属性ILeaseTransactionVoid

谢谢!

【问题讨论】:

    标签: c# .net entity-framework interface


    【解决方案1】:

    所以这似乎不是很受欢迎,但我确实设法找到了答案,所以希望有一天有人会发现这个有用:

    解决方案是保持接口签名与上面相同:

    public interface ILeaseTransaction
    {
        int ID { get; }
        DateTime Date { get; }
        decimal Amount { get; }
        ILeaseTransactionVoid Void { get; } // This throws an error
    }
    

    并通过添加一个特定于接口的属性来改变Entity类实现接口的方式,如下所示:

    public partial class Type1LeaseTransactionVoid : ILeaseTransactionVoid
    {
        ILeaseTransactionVoid ILeaseTransaction.Void
        {
            get { return (ILeaseTransactionVoid)Void; }
        }
    }
    

    【讨论】:

    • 我确实遇到了这个问题,所以我很高兴找到这个解决方案....但是我的实现出现了 2 个错误:1. (我相当于你的 Void 属性)的显式实现错误:
    • 忽略之前的评论 - 我发现了我的问题。非常感谢您发布答案 - 它在这里产生了很大的不同!
    猜你喜欢
    • 2018-07-13
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 2020-06-26
    相关资源
    最近更新 更多