简体   繁体   English

自定义隐式投射与公共财产

[英]Custom Implicit Casting vs. Public Property

Ok so I have a Top-level class that is used to monitor a bunch of different values, which range from value types to reference types. 好的,我有一个顶级类,用于监视一堆不同的值,范围从值类型到引用类型。 Now my question is what is the difference between setting up implicit casting for the top level class instead of setting up public properties. 现在我的问题是为顶级类设置隐式转换而不是设置公共属性之间的区别是什么。

Some code to illustrate. 一些代码来说明。

This: 这个:

 public static implicit operator int(TopLevel TP)
 {
       return TP.DataLevel1.DataLevel2.DataLeverl3.Data;
 }

Compared to: 相比:

 public int DataLevel3Value
 {
      get
      {
          return this.DataLevel1.DataLevel2.DataLeverl3.Data;
      }
 }

Is there a reason I would not want to do the Implicit version compared to the Property version? 与Property版本相比,我是否有理由不想使用Implicit版本? Also is the code bellow valid? 以下代码是否有效?

 (TP == 10) == (TP.DataLevel3Value == 10) == true;

I do realize the implicit conversion possibility introduces a slight lack of readability however this is a small project with only one other programmer. 我确实意识到隐式转换的可能性会导致略微缺乏可读性,但这是一个只有一个其他程序员的小项目。 We are just curious if there are serious drawbacks that would inhibit functionality of the program that we are missing. 我们只是好奇是否有严重的缺点会妨碍我们缺少的程序功能。

Definitely DO NOT write implicit casts like this. 绝对不要写这样的隐式演员表。 Implicit casts are reserved for when no data can be lost when converting from one type to another. 当从一种类型转换为另一种类型时,没有数据丢失时,保留隐式强制转换。 From the documentation : 文档

The implicit keyword is used to declare an implicit user-defined type conversion operator. implicit关键字用于声明隐式用户定义的类型转换运算符。 Use it to enable implicit conversions between a user-defined type and another type, if the conversion is guaranteed not to cause a loss of data . 如果保证转换不会导致数据丢失使用它来启用用户定义类型与其他类型之间的隐式转换。

In your example, it does cause a loss of information. 在您的示例中,它确实会导致信息丢失。 The property is clearly a better way to go. 该物业显然是一个更好的方式。

You mentioned that it reduces readability, and your absolutely right. 你提到它会降低你的可读性,而你的绝对正确。 In the vast majority of cases you should favor improved readability over any syntactic sugar which merely lets you write code with fewer character, regardless of project size. 在绝大多数情况下,您应该倾向于提高可读性而不是任何语法糖,这只能让您编写具有较少字符的代码,而不管项目大小如何。

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

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