Mam zrobić własne formatowania do wyświetlania liczb zespolonych.
Rozszerzyć tę klasę o własne formatowane. Ściślej, zaimplementować interfejs IFormattable i obsługiwać dwa rodzaje formatowania:
•domyślne (brak formatowania lub d) powinno dawać wynik
a+bi
•wektorowe (format w) powinno dawać wynik [a, b].
Przykładowy kawałek kodu:
Complex z = new Complex( 4, 3 );
Console.WriteLine( String.Format( "{0}", z ) );
Console.WriteLine( String.Format( "{0:d}", z ) );
Console.WriteLine( String.Format( "{0:w}", z ) );
powinien dać wynik
4+3i
4+3i
[4,3]
Napisałem programik ale mam pewny problem. mam metodę Format która przyjmuje 3 wartosci. Powinienem ją chyba przeciążyć na dwie wartosci żeby przy wywołaniu było Format({0:w},z).
teraz mam Format(z,{0:w},"")
ponizej kod:
public class Complex : IFormatProvider, ICustomFormatter
{
private int z1;
private int z2;
public Complex(int Z1, int Z2)
{
this.z1 = Z1;
this.z2 = Z2;
}
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format, IFormatProvider provider)
{
if (!provider.Equals(this)) return null;
if (string.IsNullOrEmpty(format))
format = "d";
if (format == "d")
return z1 + "+" + z2 + "i";
else if (format == "w")
return "[" + z1 + "," + z2 + "]";
else
return "błąd";
}
public string Format(string format,object arg,IFormatProvider formatProvider)
{
if (!formatProvider.Equals(this)) return null;
if (string.IsNullOrEmpty(format))
format = "d";
if (format == "d" || format == "0")
return z1 + "+" + z2 + "i";
else if (format == "w")
return "[" + z1 + "," + z2 + "]";
else
return "błąd";
}
public static void Main()
{
Complex z = new Complex(3, 4);
Complex z2 = new Complex(2, 111);
Console.WriteLine(String.Format(z, "{0:w}", ""));
Console.ReadKey();
}
}