How to change the class of an object dynamically in C#?

后端 未结 10 1360
囚心锁ツ
囚心锁ツ 2021-01-05 17:09

Suppose I have a base class named Visitor, and it has 2 subclass Subscriber and NonSubscriber.

At first a visitor is start off from a NonSubscriber, i.e.

<         


        
10条回答
  •  南笙
    南笙 (楼主)
    2021-01-05 17:54

    It seems like you are encoding information incorrectly into your class hierarchy. It would make more sense to use a different pattern than sub classing here. For example, use only one class (visitor, or perhaps you could name it potential subscriber, whatever seems appropriate) and encode information on the services the object is subscribed to, moving the dynamically changing behavior behind a "Strategy" pattern or some such. There's very little detail in your example, but one thing you could do in C# is to make a "subscriber" property which would change the behavior of the object when the state of the property was changed.

    Here's a contrived somewhat related example:

    class Price
    {
        private int priceInCents;
        private bool displayCents;
    
        private Func displayFunction;
    
        public Price(int dollars, int cents)
        {
            priceInCents = dollars*100 + cents;
            DisplayCents = true;
        }
    
        public bool DisplayCents
        {
            get { return displayCents; }
            set
            {
                displayCents = value;
                if (displayCents)
                {
                    this.displayFunction = () => String.Format("{0}.{1}", priceInCents / 100, priceInCents % 100);
                }
                else
                {
                    this.displayFunction = () => (priceInCents / 100).ToString();
                }
            }
        }
    
        public string ToString()
        {
            return this.displayFunction();  
        }
    }
    

提交回复
热议问题