简体   繁体   中英

override ToString() for an int element in a class

i would like to override the ToString() method for an int (that is a part of a class) so that if the value of the int is 0, the ToString() should return an empty string "" .Can this be done?

UPDATE It would be easy to just create a

public string AmountToString {
    get { if (Amount != 0) return Amount.ToString(); else return ""; }
}

i was just curious to see if it could be implemented (the ToString() ) on an primite type

Three main approaches:

Employ a (custom) Format provider

So you can use i.ToString(formatprovider);

Edit I think I found a custom format string one that works with the default .NET number format provider:

i.ToString("0;-0;"); // works

Another sample lifted from the page on The ";" Section Separator :

i.ToString("##;(##);**Zero**"); // would return "**Zero** instead

Tip:

You can d ownload the Format Utility , an application that enables you to apply format strings to either numeric or date and time values and displays the result string.

Extension method

public static string ToStringOrEmpty(this int i)
{
    return (0==i)? string.Empty : i.ToString();
}

Accessor Helper:

class X
{ 
      int member;

      public string getMember() { return (0==member)? string.Empty : member.ToString();
}

Unfortunately no. You need to have access to the class code to override any methods or properties, including the ToString method. As int is a primative type, you are not able to change the classes code (not with ease and not reliably anyway).

Your best option would be to create an Extension method:

public static class IntExtensions
{
    public static ToStringOrEmpty(this int value)
    {
        return value == 0 ? "" : value.ToString();
    }
}

Not unless it's a method of that class, you can't change the int's implementation of ToString() .

Some options:

  1. Create a method on the class.
  2. Create an extension method for int , however, you'd have to manage calling it (as opposed to ToString yourself).
  3. Another option is to create a wrapper around int, with implicit conversion operators etc., that implements ToString how you want, and use that in your class.
  4. Create or find a custom format provider that you can pass to ToString .

You can define an extension method, in the same namespace and override the behavior for int class. A sample Example :

void Main()
{
    Console.WriteLine(5.Convert()); // Prints "5"
    Console.WriteLine("Empty String" + 0.Convert());
}

// Define other methods and classes here
public static class ExtMethods{
    public static string Convert(this int value)
    {
        return value == 0 ? string.Empty : value.ToString();
    }
}

您必须在(您的)类本身上覆盖ToString方法,并在调用它时,只需在此字段为0时返回string.Empty。

return a+i==0?string.Empty:i+...

如果你编写一个继承自int的类型, 不幸的是int是一个密封类,所以你不能。

I thing, it is better to write som extension method instead...

public static string ToMyString(this int input)
{
    return input == 0 ? string.Empty : input.ToString();
}

I never heard of a way to do that before nor did I find one when searching. You can use a custom class that holds an int and has its own overridden toString(). is that relevant? or do you have to have it as an int?

you can also use

x == 0 ? "" : x.toString();

that way you get "" if 0 or the tostring

WHat you want to do is override the class whose ToString() you want to implement. Type int is a sealed class, as most base types are.

What you can do is craete a class that encapsulates int, and then implement cast operators and override the ToString() method.

This sounds like a lot of work for something so small, but that is the way to go!

Here is your class (sorry for lousy names):

struct b
{
    int myInt;
    public override string ToString()
    {
        return myInt != 0 ? myInt.ToString() : "";
    }

    public static implicit operator int(b d)
    {
        return d.myInt;
    }
    //  User-defined conversion from double to Digit
    public static implicit operator b(int d)
    {
        return new b { myInt = d };
    }
}

You can't override the ToString() method of int as you wont have access to the code, but you can create an extension method on int class with a different method name like ToString2() in which you can return empty string when value of int is zero else you can return the normal value of the int variable.

For reference on how to create extension methods on existing classes, you can refer below link:

http://msdn.microsoft.com/en-us/library/bb311042.aspx

Create an Extension for Int

public static class Ext
{
        public static string ToMyString(this int myInt)
        {
            return myInt == 0 ? "" : myInt.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