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

后端 未结 3 1759
执笔经年
执笔经年 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:36

    Jon has a good solution as usual, although I don't see what good attributes do here, since they have to be explicitly added to every subtype and they don't act like properties.

    The Dictionary approach can definitely work. Here's another way to do that, which explicitly declares that there will be one variable per subclass of BaseEntity:

    class FilteredProperties where T : BaseEntity
    {
         static public List Values { get; private set; }
         // or static public readonly List Values = new List();
         static FilteredProperties()
         {
             // logic to populate the list goes here
         }
    }
    

    The drawback of this is that it's rather difficult to pair with a GetType() call such as you might use in methods of BaseEntity. A Dictionary, or wrapper thereto which implements lazy population, is better for that usage.

提交回复
热议问题