What is the best way to define a static property which is defined once per sub-class?

后端 未结 3 1739
执笔经年
执笔经年 2021-01-12 18:56

I wrote the following console app to test static properties:

using System;

namespace StaticPropertyTest
{
    public abstract class BaseClass
    {
                 


        
3条回答
  •  攒了一身酷
    2021-01-12 19:13

    Two possible approaches:

    • Use attributes; decorate each subclass with an attribute, e.g.

      [MyProperty(5)]
      public class DerivedAlpha
      {
      }
      
      [MyProperty(10)]
      public class DerivedBeta
      {
      }
      

      That only works when they're effectively constants, of course.

    • Use a dictionary:

      var properties = new Dictionary
      {
          { typeof(DerivedAlpha), 5) },
          { typeof(DerivedBeta), 10) },
      };
      

    EDIT: Now that we have more context, Ben's answer is a really good one, using the way that generics work in C#. It's like the dictionary example, but with laziness, thread-safety and simple global access all built in.

提交回复
热议问题