C#类作为类中的一个值//模仿int行为 [英] C# Class as one Value in Class // Mimic int behaviour
问题描述
有没有办法让我的新Class模仿int或任何Valuetype的行为?
Is there a way to make my new Class mimic the behavior of an int or any Valuetype?
我想要一些东西,所以这些分配是有效的
I want something, so these assignments are valid
MyClass myClass = 1;
int i = myClass;
var x = myClass; // And here is important that x is of type int!
MyClass看起来像这样
The MyClass looks roughly like this
public class MyClass {
public int Value{get;set;}
public int AnotherValue{get;set;}
public T GetSomething<T>() {..}
}
每个MyClass分配都应将变量Value
作为类型int返回.
Every assignment of MyClass should return the Variable Value
as Type int.
到目前为止,我发现了implicit operator int
和implicit operator MyClass (int value)
.但这还不够好.
So far i found implicit operator int
and implicit operator MyClass (int value)
. But this is not 'good enough'.
我希望MyClass
实际上表现得像一个int.因此,var i = myClass
让i
成为一个整数.
I want that MyClass
realy behaves like an int. So var i = myClass
lets i
be an int.
这有可能吗?
推荐答案
如果您是这样创建从类到int的演员表:
If you´d created a cast from your class to int as this:
public static implicit operator int(MyClass instance) { return instance.Value; }
您可以隐式将MyClass
的实例强制转换为一个int:
you could implicetly cast an instance of MyClass
to an int:
int i = myClass;
但是您不能期望var
关键字猜测您实际上指的是typeof int
而不是MyClass
,所以不起作用:
However you can not expect the var
-keyword to guess that you actually mean typeof int
instead of MyClass
, so this does not work:
var x = myClass; // x will never be of type int
除此之外,我强烈不建议使用隐式强制转换,因为这两种类型没有任何共同之处.使其明确:
Apart from this I would highly discourage from an implicit cast as both types don´t have anything in common. Make it explicit instead:
int i = (int) myClass;
请参见马克·格雷夫(Marc Gravell)的出色答案为什么在隐式对象上使用显式类型转换.基本上,这是确定在相互转换时是否会丢失数据.在您的情况下,您丢失了有关AnotherValue
的任何信息,因为结果只是原始的int
.另一方面,当您使用显式强制转换时,您会声称:可以转换类型,但是我们可能会丢失原始对象的信息,因此不会在意.
See this excellent answer from Marc Gravell for why using an explicit cast over an implicit one. Basically it´s about determing if data will be lost when converting the one in the other. In your case you´re losing any information about AnotherValue
, as the result is just a primitive int
. When using an explicit cast on the other hand you claim: the types can be converted, however we may lose information of the original object and won´t care for that.
这篇关于C#类作为类中的一个值//模仿int行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!