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

后端 未结 10 1283
囚心锁ツ
囚心锁ツ 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 18:05

    You could use the GOF design patterns State or Strategy to model such an behaviour. Using these patterns, it seems during runtime as if the class of the objects has been changed.

    0 讨论(0)
  • 2021-01-05 18:08

    It seems that you have some design problems. I think that it would be better to redesign your code like:

    class Visitor
    {
        private bool isSubscriber = false;
    
        public bool IsSubscriber
        {
             get { return isSubscriber; }
        }
    
        public void Subscribe()
        {
            // do some subscribing stuff
            isSubscriber = true;
        }
    
        public void Unsubscribe()
        {
            // do some unsubscribing stuff
            isSubscriber = false;
        }
    }
    
    0 讨论(0)
  • 2021-01-05 18:12

    You cannot change the type of a variable at runtime. You need to create a new instance.

    mary = new Subscriber();
    
    0 讨论(0)
  • 2021-01-05 18:12

    Create a Subscriber constructor that takes a NonSubscriber object as a parameter, or create a method on the NonSubscriber object that returns a Subscriber to save you having to writer the mappping code in multiple places.

    0 讨论(0)
提交回复
热议问题