簡體   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