Need to add same properties in two different classes

前端 未结 3 819
被撕碎了的回忆
被撕碎了的回忆 2021-01-25 03:48

I have two classes like Class A and Class B. Class A have some properties, methods and Class B have only the properties. But both Classes have the same set of properties.

<
相关标签:
3条回答
  • 2021-01-25 04:09

    You can go with the abstract class. The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.

    Here is a simple example related to your question However you can understand and learn about Abstract classes here : Abstract Class

    using System;
    
    public class Program
    {
        public static void Main()
        {
            A objA = new A();
            objA.printA();
            B objB = new B();
            objB.printB();
    
        }
    }
    
    abstract class Parent{
    
        public int a = 5;
    
    }
    
    class A : Parent
    {
        public void printA()
        {
            Console.WriteLine("In class A, value is "+a);
        }
    }
    
    class B : Parent
    {
        public void printB()
        {
            Console.WriteLine("In class B, value is "+a);
        }
    }
    

    Output of the above program is:

    In class A, vlaue is 5
    In class B, vlaue is 5
    

    Hope this helps you.

    0 讨论(0)
  • 2021-01-25 04:19

    Or you can use keyword abstract to create a class in common for A and B.

    abstract class BaseClass   // Abstract class
    {
        public int X {get;set;} // property in common for 2 class
    }
    
    class A : BaseClass
    {
    }
    
    class B : BaseClass
    {
        public int Y {get;set;} // other property of B
    }
    
    0 讨论(0)
  • 2021-01-25 04:21

    You may achieve this by using an Interface and implementing it both in class A and class B. In the interface, define the property that is required in class A and B:

    public interface ICommonProperty
    {
       string MyProperty{ get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题