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

后端 未结 10 1284
囚心锁ツ
囚心锁ツ 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:01

    public class User
    {
        public Subscription Subscription { get; set; }
        public void HandleSubscription()
        {
            Subscription.Method();
        }
    }
    
    public abstract class SubscriptionType
    {
      public abstract void Method();
    }
    
    public class NoSubscription : SubscriptionType
    {
      public override void Method()
      {
        // Do stuff for non subscribers
      }
    }
    
    public class ServiceSubscription : SubscriptionType
    {
      public override void Method()
      {
        // Do stuff for service subscribers
      }
    }
    
    public class Service2Subscription : SubscriptionType
    {
      public override void Method()
      {
        // Do stuff for service2 subscribers
      }
    }
    

    Think the code explains my answer :)

提交回复
热议问题