我有一个用C#编写的方法,它接受一个包含XML文档的字符串,以及一个XSD流的数组。字符串文档根据XSD进行验证:
private static XmlValidationResult ValidateDocumentInternal(string document, params Stream[] xsdStreams)
{
XmlReaderSettings settings = new XmlReaderSettings
{
ValidationType = ValidationType.Schema
};
foreach (var xsdStream in xsdStreams)
{
using (xsdStream)
{
XmlReader xmlReader = XmlReader.Create(xsdStream);
try
{
settings.Schemas.Add(null, xmlReader);
}
finally
{
xmlReader.Close();
}
}
}
var validationErrors = new List<string>();
settings.ValidationEventHandler += (object sender, System.Xml.Schema.ValidationEventArgs e) =>
{
validationErrors.Add($"({e.Exception.LineNumber}): {e.Message}");
};
using (var stream = document.ToStream())
{
var reader = XmlReader.Create(stream, settings);
while (reader.Read())
{
}
}
return new XmlValidationResult
{
Success = validationErrors.Count == 0,
ValidationErrors = validationErrors
};
}
我的问题是,这种方法应该处理XSD流还是应该由调用者负责?想象一下下面的代码,它传入文档和XSD,并期望ValidateDocumentInternal
处理XSD流:
var document = GetDocument();
Stream xsd = GetXSD();
var validationResult = ValidateDocumentInternal(document, xsd);
或者应该是这样(不在ValidateDocumentInternal
中处理流):
var document = GetDocument();
using (Stream xsd = GetXSD()) {
var validationResult = = ValidateDocumentInternal(document, xsd);
}
或者我应该传递一个bool
说是否处置?
答案 0 :(得分:4)
我认为这是来电者的责任 - 这是其他人从该职能部门给出的参数。该函数无法知道它是否在另一个上下文中使用,并且它将改变它实际上是一个“副作用”...我个人强烈试图避免