从字符串转换为system.drawing.point c#

时间:2012-04-28 19:05:32

标签: c# vb.net string point typeconverter

我想将{X=-24,Y=10}生成的字符串Point.ToString();再次转换为Point?

我在保存模式下将字符串值保存在xml文件中,我希望在读取模式下再次将其读回。

7 个答案:

答案 0 :(得分:3)

var myStringWhichCantBeChanged="{X=-24,Y=10}";
var g=Regex.Replace(myStringWhichCantBeChanged,@"[\{\}a-zA-Z=]", "").Split(',');

Point pointResult = new Point(
                  int.Parse (g[0]),
                  int.Parse( g[1]));

答案 1 :(得分:2)

System.Drawing.Point根本没有定义Parse方法 - 您需要编写自己的方法,并采用此格式并返回Point结构。

System.Windows.Point确实有Parse方法,可能更适合您的需求。

但是,由于您要输出到XML,因此不需要这样做。您应该对对象图进行序列化和反序列化,这将自动处理此问题,而无需担心解析和格式化。

答案 2 :(得分:1)

您可以尝试此Point.Parse

Point pointResult = Point.Parse("-24,10");

答案 3 :(得分:1)

我今天需要这个功能,我自己,所以我只是编码了它。这是一个非常挑剔的解析器,使用“TryParse”方法。我不喜欢我称之为'懒惰'的解析,其中“blah4,9anything”会被解析为一个点。而且我不喜欢抛出错误。数据类型的'TryParse'方法对我来说非常强大。所以这是我的任何使用的实现。我唯一的要求是如果你发现了一个bug,请告诉我! :)

public static bool TryParsePoint(string s, out System.Drawing.Point p)
{   p = new System.Drawing.Point();
    string s1 = "{X=";
    string s2 = ",Y=";
    string s3 = "}";
    int x1 = s.IndexOf(s1, StringComparison.OrdinalIgnoreCase);
    int x2 = s.IndexOf(s2, StringComparison.OrdinalIgnoreCase);
    int x3 = s.IndexOf(s3, StringComparison.OrdinalIgnoreCase);
    if (x1 < 0 || x1 >= x2 || x2 >= x3) { return false; }
    s1 = s.Substring(x1 + s1.Length, x2 - x1 - s1.Length);
    s2 = s.Substring(x2 + s2.Length, x3 - x2 - s2.Length); int i = 0;
    if (Int32.TryParse(s1, out i) == false) { return false; } p.X = i;
    if (Int32.TryParse(s2, out i) == false) { return false; } p.Y = i;
    return true;
} // public static bool TryParsePoint(string s, out System.Drawing.Point p)

注意您可能还想删除或更改方法的publicstatic修饰符。但我在Program类中使用了该方法,因此我需要public static。适合自己。

答案 4 :(得分:0)

Hans Passant有正确的解决方案:不要使用Point.ToString(),这会给你那个疯狂的,不可重复使用的字符串(MSDN称之为“human-readable”)。请改用PointConverter课程。

生成字符串:

Dim myPoint As New Point(0, 0)
Dim pointConverter As System.ComponentModel.TypeConverter = _
    System.ComponentModel.TypeDescriptor.GetConverter(GetType(Point))
Dim pointAsString As String = pointConverter.ConvertToString(myPoint)

并解释上面的字符串:

Dim pointConverter As System.ComponentModel.TypeConverter = _
    System.ComponentModel.TypeDescriptor.GetConverter(GetType(Point))
Dim myNewPoint As New Point = pointConverter.ConvertFromString(pointAsString)

答案 5 :(得分:0)

请参阅PointConverter ConvertFrom方法。

答案 6 :(得分:0)

尝试一下,这就是我在项目中使用的方式。

string str = "-24,10";
Point pt = new Point(Int32.Parse(str.Split(',')[0]), Int32.Parse(str.Split(',')[1]));