C#:自定义转换为值类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1073480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#: Custom casting to a value type
提问by Andreas Grech
Is it possible to cast a custom class to a value type?
是否可以将自定义类转换为值类型?
Here's an example:
下面是一个例子:
var x = new Foo();
var y = (int) x; //Does not compile
Is it possible to make the above happen? Do I need to overload something in Foo
?
是否有可能使上述情况发生?我需要超载一些东西Foo
吗?
采纳答案by Frederik Gheysels
You will have to overload the cast operator.
您将不得不重载强制转换运算符。
public class Foo
{
public Foo( double d )
{
this.X = d;
}
public double X
{
get;
private set;
}
public static implicit operator Foo( double d )
{
return new Foo (d);
}
public static explicit operator double( Foo f )
{
return f.X;
}
}
回答by Rytmis
Create an explicit or implicit conversion:
创建显式或隐式转换:
public class Foo
{
public static explicit operator int(Foo instance)
{
return 0;
}
public static implicit operator double(Foo instance)
{
return 0;
}
}
The difference is, with explicit conversions you will have to do the type cast yourself:
不同之处在于,通过显式转换,您必须自己进行类型转换:
int i = (int) new Foo();
and with implicit conversions, you can just "assign" things:
通过隐式转换,您可以“分配”一些东西:
double d = new Foo();
MSDNhas this to say:
MSDN有这样的说法:
"By eliminating unnecessary casts, implicit conversions can improve source code readability. However, because implicit conversions do not require programmers to explicitly cast from one type to the other, care must be taken to prevent unexpected results. In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness. If a conversion operator cannot meet those criteria, it should be marked explicit." (Emphasis mine)
“通过消除不必要的强制转换,隐式转换可以提高源代码的可读性。但是,由于隐式转换不需要程序员从一种类型显式转换为另一种类型,因此必须小心防止出现意外结果。一般来说,隐式转换运算符不应该抛出异常并且永远不会丢失信息,以便可以在程序员不知情的情况下安全地使用它们。如果转换运算符不能满足这些标准,则应将其标记为显式。”(强调我的)
回答by Mark
Another possibility is to write a Parse and TryParse extension method for your class.
另一种可能性是为您的类编写 Parse 和 TryParse 扩展方法。
You'd then write your code as follows:
然后,您可以按如下方式编写代码:
var x = new Foo();
var y = int.Parse(x);
回答by arbiter
回答by Ian
I would suggest you implement the IConvertible interface as that is designed to handle this. See http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx
我建议您实现 IConvertible 接口,因为它旨在处理此问题。请参阅http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx