代码之家  ›  专栏  ›  技术社区  ›  MrFox

如何制作抽象静态属性

  •  1
  • MrFox  · 技术社区  · 7 年前

    每项财产的利益:
    -摘要;基类要求实现此属性,但未指定值。
    -静态;每个实现类型只存储一个值,而不是每个对象。

    public interface IPiece
    {
        readonly int Points;
        readonly char Letter;
    }
    
    public abstract class Piece
    {
        public static readonly int Points;
        public static readonly char Letter;
    }
    
    public class King : Piece, IPiece
    {
        public int Points = 0;
        public int Letter = 'K';
    }
    
    4 回复  |  直到 7 年前
        1
  •  2
  •   mjwills Myles McDonnell    7 年前

    解决此问题的标准模式是:

    public interface IPiece
    {
        int Points { get; }
        char Letter { get; }
    }
    
    public class King : IPiece
    {
        public int Points => 0;
        public char Letter => 'K';
    }
    

    static 从那以后 0 K 静止的

    还请注意,我已删除了您的 abstract class -它没有什么用处,因为它没有逻辑。一 抽象类 没有逻辑在概念上等同于 interface

    如果你真的想使用 静止的

    public class King : IPiece
    {
        private static int points = 0;
        private static char letter = 'K';
    
        public int Points => points;
        public char Letter => letter;
    }
    

        2
  •  1
  •   nemanja228    7 年前

    不能有静态抽象属性。类的静态成员不受多态性的约束。若您希望在抽象类中定义一个属性,该属性应由所有实现和您共享 Singleton 如果代码中没有定义它的类型,则为它键入一个包装器。然后你可以有这样的东西:

    public abstract class Piece // or interface
    {
        public SingletonIntWrapper Points { get; }
        public SingletonCharWrapper Letter { get; }
    }
    
        3
  •  1
  •   Matthew Brubaker    7 年前

    public interface IPiece
    {
        int Points {get;} // readonly properties in interfaces must be defined like this
        char Letter {get;}
    }
    

    您还需要让抽象类从接口继承,以便它能够访问其中定义的属性。因为它是一个抽象类,所以必须将属性标记为抽象类

    public abstract class Piece : IPiece
    {
        public abstract int Points {get;}
        public abstract char Letter {get;}
    }
    

    public class King : Piece
    {
        public override int Points {get; private set;} = 0;
        public override char Letter {get; private set;} = 'K';
    }
    

    看一看 here

        4
  •  0
  •   Wouter    7 年前

    你应该使用 const static readonly backingfield。(有区别)。抽象类和接口也是冗余的。要么让您的所有片段都源自片段,要么让它们实现IPiece。

    public interface IPiece
    {
        int Points { get; }
        char Letter { get; }
    }
    
    public abstract class Piece : IPiece
    {
        public abstract int Points { get; }
        public abstract char Letter { get; }
    }
    
    public class King : Piece
    {
        public const int POINTS = 0;
        public const char LETTER = 'K';
    
        public override int Points { get { return POINTS; } }
        public override char Letter { get { return LETTER; } }
    }
    

    注: 现在你仍然不能使用公共资源 常数 静态只读 以非常有用的方式。因为如果没有实例,就无法获得值的定义。例如,在枚举所有值以确定所需内容时,无法获取King.LETTER的值 Piece 根据一个字符构造。

    推荐文章