[英]Need to add same properties in two different classes
I have two classes like Class A and Class B. Class A have some properties, methods and Class B have only the properties.我有两个类,比如 A 类和 B 类。 A 类有一些属性、方法,而 B 类只有属性。 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.我的问题是,如果我在 A 类中添加任何新属性,我也需要在 B 类中添加它。 If I did not add means, need to show error.
如果我没有添加手段,需要显示错误。 How can I achieve this through C#?
我怎样才能通过 C# 实现这一点?
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:您可以通过使用接口并在 A 类和 B 类中实现它来实现这一点。在接口中,定义 A 类和 B 类所需的属性:
public interface ICommonProperty
{
string MyProperty{ get; set; }
}
Or you can use keyword abstract
to create a class in common for A and B.或者您可以使用关键字
abstract
为 A 和 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
}
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.
abstract 关键字使您能够创建不完整且必须在派生类中实现的类和类成员。
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.希望这对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.