价值未达到预期
我正在构建一个使用文件来配置某些字体的应用程序。它是这样的:
Font = Verdana
Size = 12
Style = Bold
我的代码是这样的:
openDialog.ShowDialog();
string file = openDialog.FileName;
StreamReader reader = new StreamReader(file);
while (reader.Peek() <= 0)
{
string line = reader.ReadLine();
string[] data = Split(new[] { '=' });
// property is in data[0]
// value is in data[1]
TextFont = data[1];
TextSize = data[3];
TextSt = data[5];
}
reader.Close();
reader.Dispose();
并像这样使用它:
textBox1.Font = new System.Drawing.Font(TextFont, 12F, FontStyle.Bold);
但是当我执行它时,我得到了这个错误:
参数异常
价值未达到预期
然后我有两个问题:
- 我该如何解决这个问题?
- 如何在
Font
方法中使用浮点数来代替TextSize
的字符串来实现它?
谢谢。
I'm building a application that uses a file to configure some fonts. It's like this:
Font = Verdana
Size = 12
Style = Bold
And my code is like this:
openDialog.ShowDialog();
string file = openDialog.FileName;
StreamReader reader = new StreamReader(file);
while (reader.Peek() <= 0)
{
string line = reader.ReadLine();
string[] data = Split(new[] { '=' });
// property is in data[0]
// value is in data[1]
TextFont = data[1];
TextSize = data[3];
TextSt = data[5];
}
reader.Close();
reader.Dispose();
And using it like this:
textBox1.Font = new System.Drawing.Font(TextFont, 12F, FontStyle.Bold);
But when I execute it I got this error:
ArgumentException
Value does not fall within the expected
Then I have two questions:
- How can I solve this problem?
- How can I use instead of a string for
TextSize
use a float to implement it in theFont
method?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能还遇到数据转换问题:Split() 方法返回一个字符串数组,但 TextSize 是浮点数,而 TextStyle 是枚举 (FontStyle)。虽然我们人类可以很容易地看出数字 12 和字符串“12”至少是相关的,但编译器却要挑剔得多。
您可以尝试对 TextSize 进行此操作:
处理 TextStyle 可能会有点棘手,因为您必须将字符串值与不同的枚举值进行比较。例如,要检测“粗体”样式,您可以编写:
干杯!
谦虚的程序员
,,,^..^,,,
You may also have data conversion issues: the Split() method returns an array of strings, but TextSize is a float, while TextStyle is an enumeration (FontStyle). While we as human beings can easily tell that the number 12 and the string "12" are at least related, compilers are a lot pickier.
You might try this for the TextSize:
Handling the TextStyle might be a little trickier, because you'll have to compare the string value against the different enumerated values. For example, to detect the "Bold" style, you would write:
Cheers!
Humble Programmer
,,,^..^,,,
您正在读取一行,然后尝试从中获取三个值。看看评论:
然后你正在使用 data[1]、data[3] 和 data[5]...
你可能想要类似的东西:
You're reading a single line, but then trying to take three values from it. Look at the comment:
You're then using data[1], data[3] and data[5]...
You probably want something like:
Jon Skeet 已经回答了你的第一个问题,所以对于你的第二个问题(如何将字体大小解析为浮点数):
其中 s 是包含字体大小的字符串。
Jon Skeet already answered your first question, so for your second one (how to parse the font size as a float):
where s is the string containing the font size.