简体   繁体   English

C#:什么时候应该使用显式运算符而不是隐式运算符覆盖?

[英]C# : when should we use explicit instead of implicit operator override?

I've seen MSDN tutorial about implicit and explicit operators. 我看过有关隐式和显式运算符的MSDN教程。 I've made some tests and it works very well. 我进行了一些测试,效果很好。

I know the difference between them (syntaxily speaking), but I do not know the best way to use them. 我知道它们之间的区别(从语法上来说),但是我不知道使用它们的最佳方法。

My question could have been : "What kind of convertions must be done using a cast?" 我的问题可能是:“ 必须使用演员表进行哪种转换?”

For now, I just haven't overriden implicit when the result can be null.. 现在,当结果可以为null时,我只是没有覆盖隐式。

Example: 例:

struct TypeRef
{
    // If TypeRef is constructed with a type, will reference the given type.
    // If TypeRef is constructed with a string, will be the result of 'Type.GetType(theString)' (if the type doesn't exist: null)
    public readonly Type TypeIfExists;

    // If TypeRef is constructed with a type, will be the result of theType.Name
    // If TypeRef is constructed with a string, will reference this string.
    public readonly string TypeName;

    // Can be constructed by a string or a Type.
    // Can be converted from a string or a Type implicitely and explicitely
    // Can be converted to a string implicitely and explicitely
    // Can be converted to a Type explicitely only
}

TypeRef tr1 = "SomeType";
TypeRef tr2 = typeof(SomeType);
TypeRef tr3 = "ThisTypeDoesntExist";
Type t1 = (Type)tr1;
Type t2 = (Type)tr3; // Will be null.
string s1 = (string)tr1;
string s2 = tr1;

Thank you :) 谢谢 :)


Edit: Asked the the question more clearly :p 编辑:问的问题更清楚:p

I don't think there is a technical reason, more of an "API" reason. 认为没有技术原因,更多是“ API”原因。

From the MSDN article on explicit (emphasis mine): 从有关显式(强调我的)的MSDN文章中:

The explicit keyword declares a user-defined type conversion operator that must be invoked with a cast 显式关键字声明用户定义的类型转换运算符, 必须使用强制类型转换对其进行调用

So if you want the users of your class to be able to convert without a cast, don't overide explicit. 因此,如果您希望班级的用户能够在不进行强制转换的情况下进行转换,请不要覆盖显式。 There are arguments about casting and readability I guess. 我猜有一些关于转换和可读性的争论。

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

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