[英]Indexer explicit implemented IFormattable
我为自己编写了一个索引器,它可以工作,但是一旦我显式实现“ IFormatable”,它就不再起作用。
为什么它不起作用以及如何显式使用它?
这是我尝试的:
/// <summary>
/// Example of Coordinates for 3 dimensions.
/// </summary>
public class Coordinates:IFormattable
{
#region Constructor
public Coordinates(int x, int y, int z)
{
_x = x;
_y = y;
_z = z;
_length = 3;
}
#endregion
#region IFormattable implemented
/// <summary>
/// Formating custom string
/// </summary>
/// <param name="format">Format("A"-all value,...,"H"-)</param>
/// <param name="formatProvider">Different culture</param>
/// <returns></returns>
public string IFormattable.ToString(string format, IFormatProvider formatProvider)
{
if (format==null)
{
return ToString(); //Fallbasck
}
else
{
switch (format.ToUpper())//gross, kleinschreibung egal
{
case "A": return ToString();
case "X": return _x.ToString();
case "Y": return _y.ToString();
case "Z": return _z.ToString();
case "H": return String.Format("{0:h}", ToString());
default:
throw new FormatException(String.Format("Format {0} is not defined.", format));
}
}
}
public string ToString(string format)
{
return ToString(format, null); //Error occurs here
}
#endregion
#region overWriteToString
/// <summary>
/// will be called implicit
/// </summary>
/// <returns>[x,y,z]</returns>
public override string ToString()
{
return String.Format("[{0},{1},{2}]",_x,_y,_z);
}
#endregion
#region Properties
private int _x;
public int X
{
get { return _x; }
set { _x = value; }
}
private int _y;
public int Y
{
get { return _y; }
set { _y = value; }
}
private int _z;
public int Z
{
get { return _z; }
set { _z = value; }
}
private int _length;
public int Length
{
get { return _length; }
}
#endregion
#region Indexer
/// <summary>
/// My own indexer for x,y,z
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public int this[int val]
{
get
{
switch (val)
{
case 0: return _x; ;
case 1: return _y; ;
case 2: return _z; ;
default:
throw new IndexOutOfRangeException("Indexer not avaiable.");
}
}
//kann auch setter haben
}
#endregion
}
我正在详细学习C#。
错误发生在这里:
public string ToString(string format)
{
return ToString(format, null); //Error occurs here
}
通过显式实现ToString(string format, IFormatProvider formatProvider)
,您只能通过编译时类型为IFormattable
的引用来调用它。
您可以使用this
:
return ((IFormattable)this).ToString(format, null);
要么:
IFormattable formattable = this;
return formattable.ToString(format, null);
我可能会在代码中添加注释,以解释为什么要进行强制转换,因为直到您注意到该方法显式实现了IFormattable.ToString
才知道这IFormattable.ToString
。
顺便说一句,您是否有任何理由要明确实现它? 感觉应该可以访问-您应该使用传入的IFormatProvider
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.