Need to add same properties in two different class

2020-04-19 19:51发布

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.

My Question is, If I add any new property in Class A, I need to add that in Class B also. If I did not add means, need to show error. How can I achieve this through C#?

标签: c#
3条回答
再贱就再见
2楼-- · 2020-04-19 20:41

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.

查看更多
女痞
3楼-- · 2020-04-19 20:45

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; }
}
查看更多
smile是对你的礼貌
4楼-- · 2020-04-19 20:49

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
}
查看更多
登录 后发表回答