繁体   English   中英

不返回对象的多种数据类型的解析器

[英]Parser for multiple data types without returning object

我正在为一些以 XML 形式给出的数据构建一个解析器,类似于:

获取路径%windir%\\system32\\calc.exe并检索它的CreationTime

FileInfo的一个小问题是我正在检索的对象类型(上面示例中的FileInfo )和我正在读取的属性的数据类型(上面示例中的CreationTimeDateTime )并不总是相同的。

例如:仅在FileInfo对象上,我可能会被要求:

  • bool Exists
  • DateTime CreationTime
  • DateTime LastWriteTime
  • long Size
  • Version Version

其他对象类型可能是FolderInfoRegistryKeyRegistryValue类的东西

考虑到这一点,我创建了以下代码:

public interface IPropertyRetriever<out T>
{
    public string Name { get; }

    public Property Property { get; }

    public T RetrieveProperty();
}

public enum Property
{
    Count,
    DateCreated,
    DateModified,
    RegistryKeyExists,
    RegistryValueExists,
    Size,
    Value,
    Version
}

public class FilePropertyRetriever<T> : IPropertyRetriever<T>
{
    public FilePropertyRetriever(string name, Property property, string path, bool is64Bit)
    {
        Name = name;
        Property = property;
        Path = path;
        Is64Bit = is64Bit;
    }

    public string Name { get; }

    public Property Property { get; }

    public string Path { get; }

    public T RetrieveProperty()
    {
        var file = ...
        // Do something to retrieve FileInfo, 
        // assumes if it got to code below FileInfo.Exists is true

        return (T) (object) (Property switch
        {
            Property.Count => file.Exists,
            Property.DateCreated => file.CreationTime,
            Property.DateModified => file.LastWriteTime,
            Property.Size => file.Length,
            Property.Version => Version.TryParse(FileVersionInfo.GetVersionInfo(Path).ProductVersion,
                out var version)
                ? version
                : null
        });
    }
}

我知道我的T RetrieverProperty()方法并不是很好的编程 - 我告诉我的方法我希望它返回什么类型,而实际上它已经知道并使用泛型转换为正确的类型(并首先将其装箱如果DateTime / long / int ),但我真的想不出更好的方法来做到这一点。

关于如何改进这一点的任何建议?

PS: RetrieveProperty()之所以不接受参数而是使用属性,是因为创建对象的设备和运行方法的设备不一样,对象被序列化发送过来。

为什么 IPropertyRetriever 不能是这样的:

public interface IPropertyRetriever
{
    public string Name { get; }

    public int Count {get;}
    public DateTime DateCreated {get;}
    public DateTime DateModified {get;}
    public bool RegistryKeyExists {get;}
    public bool RegistryValueExists {get;}
    public long Size {get;}
    //etc    
}

并将其称为不同的 IFileInformation。 或者为具有基本接口的不同对象返回不同的接口,因为并非所有上述属性都与所有对象相关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM