问题
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!
The MyClass looks roughly like this
public class MyClass {
public int Value{get;set;}
public int AnotherValue{get;set;}
public T GetSomething<T>() {..}
}
Every assignment of MyClass should return the Variable Value
as Type int.
So far i found implicit operator int
and implicit operator MyClass (int value)
. But this is not 'good enough'.
I want that MyClass
realy behaves like an int. So var i = myClass
lets i
be an int.
Is this even possible?
回答1:
If you´d created a cast from your class to int as this:
public static implicit operator int(MyClass instance) { return instance.Value; }
you could implicetly cast an instance of MyClass
to an int:
int i = 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;
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.
回答2:
Is this even possible?
No.
You can convert and cast types to other types implicitly and explicitly, but to have one type supersede another type without any inheritance or interface implementation flies in the face of object-oriented programming principles.
The var
keyword is a convenience that tries to guess the type of a value with as much precision as possible. Therefore it can't be forced to represent int
when the type is MyClass
.
You might consider something like this: var x = (int) myClass;
来源:https://stackoverflow.com/questions/47311450/c-sharp-class-as-one-value-in-class-mimic-int-behaviour