Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

operators - C# Class as one Value in Class // Mimic int behaviour

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...