简体   繁体   中英

Implicit operator for int?

I've learned to use implicit operators for my classes.

Now I want to do something like this:

public static implicit operator string(int val)
{
    return "The value is: " + val.ToString(); // just an nonsense example
}

However this is wrong. Compiler says:

User-defined conversion must convert to or from the enclosing type

How can I workaround this?

My goal is to be able to run code like this:

int x = 50;
textbox1.Text = x; // without using .ToString() or casting

You can't add an operator outside of the class of either the parameter or the return type of the operator.
In other words: You can't add an operator that converts between two types that you both don't control.

The compiler error you get is very explicit about this:

User-defined conversion must convert to or from the enclosing type

So, what you are trying to achieve here is simply not possible.
Your best option probably is an extension method on int that performs the conversion and returns a string .

You might want to consider an alternative approach.

You could write an extension method on Control like so:

public static class ControlExt
{
    public static void SetText(this Control self, object obj)
    {
        self.Text = obj.ToString();
    }
}

Then your code would become:

int x = 50;
textbox1.SetText(x);

It would of course work with any type, not just ints:

textbox1.SetText(DateTime.Now);

You need to add implicit operator as a member of the class. Since you do not have control over int class; it is not possible to add an implicit operator to int class.

You may either write a wrapper for int or create a new extension method to convert int to string directly (which has already been defined as ToString() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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