我想将UDT(用户定义类型)的所有字段作为字符串返回。
我的UDT类型如下所示:
public class MyPointF
{
public float X { get; set; }
public float Y { get; set; }
public MyPointF(float x, float y)
{
this.X = x;
this.Y = y;
}
}
我想使用这样的类型:
MyPointF point1 = new MyPointF(10, 20);
System.Console.WriteLine(point1);
此代码的返回应如下所示:
{10, 20}
当然,我还需要访问point1.X
和point1.Y
作为浮点值。任何提示如何解决这个问题都会很棒。
答案 0 :(得分:2)
因此,您需要在ToString
类中使用override
PointF
方法,如下所示:
public override string ToString()
{
return "{ " + X.ToString(CultureInfo.InvariantCulture) + " ," + Y.ToString(CultureInfo.InvariantCulture) + " }";
}
答案 1 :(得分:1)
试试这个:
class Program
{
static void Main(string[] args)
{
PointF point1 = new PointF(10, 20);
System.Console.WriteLine(point1);
Console.Read();
}
}
public class PointF
{
public float X { get; set; }
public float Y { get; set; }
public PointF(float x, float y)
{
this.X = x;
this.Y = y;
}
public override string ToString()
{
return "{ " + X.ToString(CultureInfo.InvariantCulture) + " ," + Y.ToString(CultureInfo.InvariantCulture) + " }";
}
}