简体   繁体   English

使用派生类常量的基类静态方法

[英]Base class static method using constants of derived class

I'm a bit new to c#. 我对c#有点新鲜。 Is the following pattern viable or do I need to rethink things: 以下模式是否可行或我是否需要重新思考:

public abstract class Foo{
    abstract const Format Format;
    public static GetFormat(){
        return <Format configured by derived class> 
    }
}

public class JsonFoo:Foo{
    const Format Format = Format.JSON;
}

public class XmlFoo:Foo{
    const Format Format = Format.XML;
}

I've tried to resolve it several ways buy I always run in to static can not be abstract/virtual etc. 我试图解决它几种方式购买我总是运行静态不能抽象/虚拟等。

(The code above is just to illustrate the problem) (上面的代码只是为了说明问题)

Edit: 编辑:

So i want to build an abstract base class with most of my logic, and then create light weight derived classes. 所以我想用我的大部分逻辑构建一个抽象基类,然后创建轻量级派生类。 All most all of the operations are identical but with minor differences (such as using a different format (the real case is accessing different DbSets on a common DbContext)). 所有大多数操作都是相同的,但差别很小(例如使用不同的格式(真实情况是在公共DbContext上访问不同的DbSet))。

Some of the operations are very similar (in the DbSet context, find object by id, find all etc...) 一些操作非常相似(在DbSet上下文中,通过id查找对象,查找所有等...)

You've done strange construction. 你做了奇怪的建设。 You should write something like: 你应该写一些类似的东西:

public enum Format{XML,JSON}
public abstract class Foo
{
    public abstract Format Format { get; }
}
public class JsonFoo : Foo
{
    public override Format Format
    {
        get { return Format.JSON; }
    }
}
public class XmlFoo : Foo
{
    public override Format Format
    {
        get { return Format.XML; }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM