繁体   English   中英

解析使用反射从字符串中获得的任何原始类型

[英]Parse any primitive type garnered using Reflection from a string

我正在从文本文件中检索值以构建几种不同类型的对象,并且我想要一种为这些对象填充属性值的中心方法。 我希望结果值能够从 C# 的强类型中受益,这意味着解析值。

步骤是

  • 读取文本文件的键值对
  • 获取我使用反射构建的类型的所有属性的列表。
  • 将属性值设置为其对应的键值对,将基于字符串的值转换为属性类型的值。

我目前的实现(有效)是:

 public void SetPrimitive(PropertyInfo property, T product, string value)
    {
        if (property.PropertyType == typeof(bool))
        {
            property.SetValue(product, bool.Parse(value));
        }
        else if (property.PropertyType == typeof(int))
        {
            property.SetValue(product, int.Parse(value));
        }
        else if (property.PropertyType == typeof(double))
        {
            property.SetValue(product, double.Parse(value));
        }
        else if (property.PropertyType == typeof(char))
        {
            property.SetValue(product, char.Parse(value));
        }
        else if (property.PropertyType == typeof(float))
        {
            property.SetValue(product, float.Parse(value));
        }
        else if (property.PropertyType == typeof(long))
        {
            property.SetValue(product, long.Parse(value));
        }
        else if (property.PropertyType == typeof(short))
        {
            property.SetValue(product, short.Parse(value));
        }
        else if (property.PropertyType == typeof(string))
        {
            property.SetValue(product, value);
        }
        else
        {
            throw new Exception($"Invalid type '{property.PropertyType}'. This class will need to be extended to support this.");
        }

正如你所看到的,这不是很可扩展,而且相当冗长。

我已经尝试使用 Convert 或 TypeConverters,正如在几个类似的问题中看到的那样,来解析适当的值并只是简单的类型转换,但是,与提出这些问题的开发人员不同,我正在检索类型以通过反射使用 'TypeOf (T).GetProperties' 并且它似乎不愿意转换该值,编译器抱怨它不是可识别的类型。 尽管它能够在上面的各种 if 语句中确认或拒绝对象类型,但仍然如此。

我的理论是这样的:它在编译时不知道,因为该方法正在构建直到运行时才知道的各种不同类型。 因此,我试图围绕 property.PropertyType 进行编码会导致编译器混淆。 但是,它可以轻松地将任何类型与另一种类型进行匹配,并确认/拒绝是否匹配。

有没有一种特定的方法可以写这个来让 TypeConverter 或 Convert 按预期工作? 我希望这适用于所有开箱即用的原语,并让其他开发人员添加到它,如果他们希望能够设置更复杂的类型。

TLDR; 我有一个工作方法,但它很混乱,感觉应该有更好的方法来做到这一点。

因此,可以通过使用 TypeCodes 以这种方式转换类型。 更具体地说,通过将字符串解析为相应的枚举。 TypeCodes 包括所有原始类型(这是我的最低要求),同时还能够解析一些常见但非原始(相对)复杂类型,例如 DateTime。

        public void SetProperty(PropertyInfo property, string value)
    {
        //Get the type we need to cast to.
        Enum.TryParse(property.PropertyType.Name, true, out TypeCode enumValue); //Get the type based on typecode
        //Cast to that type
        var convertedValue = Convert.ChangeType(value, enumValue); //Convert the value to that of the typecode
        //Assign
        property.SetValue(this, convertedValue); // Set the converted value

它将我限制在枚举中列出的类型,但它工作得相当好并且更干净。

手动将这些与所有这些类型进行手动比较并为每个类型添加额外的逻辑可能会很好,但对于一个包罗万象的通用解决方案,我认为这绝对是一个进步!

暂无
暂无

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

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