/*-------------------------------------------------------------------------
* 功能描述:ParseInstance
* 作者:xulisong
* 创建时间: 2019/6/13 15:04:06
* 版本号:v1.0
* -------------------------------------------------------------------------*/
using System.Collections.Generic;
using System.Linq;
using RevitExport.Export;
namespace RevitExport.Parse
{
/*
* 最好由导出类控制,导出的开始和结束。这样有一个好处是可以挂接多个解析类。
*/
///
/// 解析实例
///
public class ParseInstance where C:ParseContext
{
public ParseInstance(C context,List> parsers)
{
Context = context;
Parsers = parsers;
InitFastFilter();
}
protected Dictionary> FastFilter { get; set; }
protected List> Parsers { get; set; }
protected void InitFastFilter()
{
FastFilter = new Dictionary>();
foreach (var parseElement in Parsers)
{
var keys = parseElement.FastIndex();
foreach (var key in keys)
{
if (!string.IsNullOrWhiteSpace(key))
{
FastFilter[key] = parseElement;
}
}
}
}
protected virtual IParseElement GetMatchParser(ElementWrapper wrapper)
{
if (FastFilter.TryGetValue(wrapper.Category, out IParseElement parser))
{
return parser;
}
var currentParser = Parsers.FirstOrDefault(p => p.Match(wrapper));
return currentParser;
}
public virtual List ParseElement(ElementWrapper elementWrapper)
{
var currentParser = GetMatchParser(elementWrapper);
if (currentParser != null)
{
return currentParser.Parse(elementWrapper, Context);
}
return null;
}
#region 解析元素相关
public virtual void ParseElement(object sender, ExportArgs e)
{
if (!Parsers.Any())
return;
ElementWrapper element = e.ElementWrapper;
ParseElement(element);
}
///
/// 当前解析上下文
///
public C Context { get;protected set; }
///
/// 解析数据
///
///
///
public virtual bool Parse(ExportInstance export)
{
try
{
BindingExport(this, export);
Context.Export = export;
return export.Export();
}
finally
{
export.ParseElement -= ParseElement;
}
}
public static void BindingExport(ParseInstance instance, ExportInstance export)
{
export.ParseElement -= instance.ParseElement;
export.ParseElement += instance.ParseElement;
}
#endregion
}
}