[英]Encapsulation C# Best practices
just for clarification and for good code practices.只是为了澄清和良好的代码实践。 I understand the concept of encapsulation, but can you tell me the difference between these two codes and in which scenario would you use them.
我理解封装的概念,但是您能告诉我这两种代码之间的区别以及您将在哪种情况下使用它们吗? Thanks.
谢谢。 PS: I am not looking for links answers, I just want your honest opinion.
PS:我不是在寻找链接答案,我只是想要您的诚实意见。
Code 1:代码 1:
class Program
{
static void Main(string[] args)
{
Car ObjCar = new Car();
printVehicledetails(ObjCar);
}
private static void printVehicledetails(Vehilce vehicle)
{
Console.WriteLine("Here are the Vehicles' details: {0}", vehicle.FormatMe());
}
}
abstract class Vehilce
{
protected string Make { get; set; } //here
protected string Model { get; set; } //here
public abstract string FormatMe();
}
class Car : Vehilce
{
public override string FormatMe()
{
return String.Format("{0} - {1} - {2} - {3}", Make, Model);
}
}
Code 2:代码 2:
class Program
{
static void Main(string[] args)
{
Car ObjCar = new Car();
printVehicledetails(ObjCar);
}
private static void printVehicledetails(Vehilce vehicle)
{
Console.WriteLine("Here are the Vehicles' details: {0}", vehicle.FormatMe());
}
}
abstract class Vehilce
{
public string Make { protected get; protected set; } //here
public string Model { protected get; protected set; } //here
public abstract string FormatMe();
}
class Car : Vehilce
{
public override string FormatMe()
{
return String.Format("{0} - {1} - {2} - {3}", Make, Model);
}
}
There is a common approach: separate data and logic.有一个通用的方法:分离数据和逻辑。 In that case you should make properties public (maybe with private setters) and put formatting somewhere else, for example, in extension method.
在这种情况下,您应该公开属性(可能使用私有设置器)并将格式放在其他地方,例如,在扩展方法中。
That totally depends on your context, wheather you need to access the properties from outside of any derived class or not.这完全取决于您的上下文,您是否需要从任何派生类外部访问属性。 That´s the only difference on them, in last case you can access the properties only within
Vehicle
-class, wheras in the first you can access them from anywhere.这是它们的唯一区别,在最后一种情况下,您只能在
Vehicle
类中访问属性,而在第一种情况下,您可以从任何地方访问它们。
Btw.: Providing a access-modifier for both getter AND setter for a property will result in the following compile-time error.顺便说一句:为属性的 getter 和 setter 提供访问修饰符将导致以下编译时错误。
"Cannot specify accessibility modifiers for both accessors of the property..."
“无法为属性的两个访问器指定可访问性修饰符......”
The following works however:然而,以下工作:
protected string Make { get; set; } //here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.