【问题标题】:Abstract class in LINQ2SQL for sharing common methodsLINQ2SQL 中用于共享常用方法的抽象类
【发布时间】:2010-08-12 04:10:37
【问题描述】:

我在尝试在 linq2sql 设计器创建的两个类之间实现共享方法/属性时遇到问题。

我的两个类有两个主要属性(来自 db 模型):

public partial class DirectorPoll
{
    public bool Completed {get; set;}
    public bool? Reopen { get; set; }
    //more properties
}

public partial class StudentPoll
{
    public bool Completed {get; set;}
    public bool? Reopen { get; set; }
    //more properties
}

现在例如我创建一个抽象类:

public abstract class GenericPoll
{
    public abstract bool Completed { get; set; }
    public abstract bool? Reopen { get; set; }

    public bool CanEdit
    {
        get
        {
            if (Completed == false) return true;
            if (Reopen.GetValueOrDefault(false) == false) return false;
            return true;
        }
    }
}

然后

public partial class DirectorPoll : GenericPoll
public partial class StudentPoll: GenericPoll

但是当我尝试编译时,它显示“Director 没有实现继承的抽象成员 GenericPoll.Completed.get”。但它就在那里。所以我认为我不得不对设计器自动生成的属性进行覆盖,但是如果我稍后更新数据库并重新编译它会给我同样的错误。

我想我可能在这里遗漏了一些东西,但我尝试了不同的方法但没有成功。 ¿ 那么,除了在我的每个部分类中实现 CanEdit 之外,我还能在这里做什么?谢谢

【问题讨论】:

    标签: c# linq-to-sql abstract-class


    【解决方案1】:

    它不是作为override 实现的,所以不算。但是,隐式接口实现确实很重要,所以这是可行的:

    partial class DirectorPoll : IGenericPoll {}
    partial class StudentPoll : IGenericPoll {}
    public interface IGenericPoll
    {
        bool Completed { get; set; }
        bool? Reopen { get; set; }
    }
    public static class GenericPoll {
        public static bool CanEdit(this IGenericPoll instance)
        {
            return !instance.Completed || instance.Reopen.GetValueOrDefault();
        }
    }
    

    【讨论】:

    • 我们是坟墓的博格。害怕我们。
    【解决方案2】:

    一个选项:创建一个包含CompletedReopen 的接口,使类实现该接口(通过部分类的手动位),然后编写一个扩展该接口的扩展方法。我认为应该可行:

    public interface IPoll
    {
        bool Completed {get; set;}
        bool? Reopen { get; set; }
    }
    
    // Actual implementations are in the generated classes;
    // no need to provide any actual code. We're just telling the compiler
    // that we happen to have noticed the two classes implement the interface
    public partial class DirectorPoll : IPoll {}
    public partial class StudentPoll : IPoll {}
    
    // Any common behaviour can go in here.
    public static class PollExtensions
    {
        public static bool CanEdit(this IPoll poll)
        {
            return !poll.Completed || poll.Reopen.GetValueOrDefault(false);
        }
    }
    

    诚然,它必须是一个方法而不是一个属性,因为没有扩展属性之类的东西,但这并不是什么难事。

    (我相信我在CanEdit 中对您的逻辑的重构是正确的。所有那些明确的真假都在我脑海中浮现;)

    【讨论】:

    • 大声笑;我喜欢我们俩如何与讨厌的return 作斗争;p 你的! 放错地方了,顺便说一句。
    • @Marc:Doh - 那是因为第一次忘记包含poll :)
    • 我也注意到了;我忙于简化,无法发表评论;p
    • 很抱歉进行了明确的布尔比较,有时它有助于我在睡眠不足时理解程序流程^^
    • @Fransisco - 如果它更容易理解,那很好 - 但对于外部观察者来说,这是“计算负数”时间;p
    猜你喜欢
    • 1970-01-01
    • 2011-02-09
    • 2014-12-24
    • 2015-08-02
    • 2012-09-21
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多