简体   繁体   English

为什么要将变量声明为以类命名的类型

[英]Why would you declare a variable as a type named after a class

Using C# as an example.以 C# 为例。 Say there is a class named ExampleClass and the variable is just value.假设有一个名为 ExampleClass 的类,变量只是值。 Why would one declare a variable like this为什么要声明一个这样的变量

private ExampleClass value;

You wouldn't declare a variable named value unless there was some unavoidable requirement to do so.除非有一些不可避免的要求,否则您不会声明名为value的变量。

The reason why is because it is not meaningfully named .原因是因为它没有有意义的命名

When we name variables meaningfully, our code becomes self-documenting .当我们有意义地命名变量时,我们的代码就变成了自文档化的 Well documented code is always worthy goal.有据可查的代码始终是有价值的目标。

This is a field and can be declared inside a class.这是一个字段,可以在类中声明。 Example:例子:

private class Test
{
    private int _customField;
}

_customField is my field with type int (instead of ExampleClass ). _customField是我的类型为int (而不是ExampleClass )的ExampleClass People use it to make something more accessible since C# isn't just functions, it's OOP.人们使用它来使某些东西更易于访问,因为 C# 不仅仅是函数,它还是 OOP。

There is a thing called Primitive Obsession .有一种东西叫做原始痴迷 Using a class/specific type here is the solution to it.在这里使用类/特定类型是解决方案。

If you use a class, you got all the Compiler Type checking to help you avoid invalid values.如果你使用一个类,你会得到所有的编译器类型检查来帮助你避免无效的值。

Take this Enum vs Integer question for examples.这个 Enum vs Integer问题为例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM