我使用一个程序来读取数据从XML文件与此类似:为什么我的演员无效?
<VerificationSample X1 = "1" X3 = "3" ../>
使用此电话:
XmlReader reader = XmlReader.Create(path);
reader.ReadToFollowing("VerificationSample");
this.X1 = (double)FileStructure.GetAttributeSafe(reader, "X1", typeof(double)); // exists
this.X2 = (double)FileStructure.GetAttributeSafe(reader, "X2", typeof(double)); // doesn't exist
然而,一些属性可能不存在,所以我处理使用它里面这个例程该属性读卡器功能定义:
public static object GetAttributeSafe(XmlReader reader, string attributeName, Type objectType)
{
// ..
string value = reader.GetAttribute(attributeName);
if (value != null) // attribute exists
{
if (objectType != typeof (string))
{
var converter = TypeDescriptor.GetConverter(objectType);
returnValue = converter.ConvertFrom(value);
}
else // is already a string and doesn't need to be converted
{
return value;
}
}
else // attribute doesn't exist
{
return "0";
}
}
如果属性不存在,程序弹出一个错误:
Specified cast is not valid
我的错误是什么?
如果该属性不存在,那么你的方法返回*'string' *'“0”'。这不能转换为“双”。 –
@john,但是如果读者从文件中读取“0”,这是一个字符串。有用。如果我做这个'value =“0”;返回值;'它也行不通。为什么? –
当您从文件中读取“0”时,您会遇到一些麻烦,将其转换为请求的类型。当请求的属性不存在时,您不会运行该代码路径。 –