在c#中动态设置属性类型

时间:2012-11-02 11:18:13

标签: c# parsing reflection types properties

我的数据流出现以下问题:

数据流由字典组成,我想解析它并动态指定值的类型。

即。我的数据流包括:

  • “date”,“01.01.2000”
  • “name”,“joe”
  • “alive”,“true”
  • “health”,“100”

现在我想根据这个数据流设置泛型类的属性:

class GenericClass
{
    Hashtable genericAttributes;
}

是否有可能通过反射将数据流的值设置为正确的类型?

我可以试试像:

DateTime.TryParse(date, out myDate);

表示日期时间对象,但我认为这在尝试解析双精度数,浮点数,int16s,int32s,uint16,...时不会起作用。

对此有些想法?

谢谢和问候

1 个答案:

答案 0 :(得分:1)

我的猜测是,他们都是IConvertible,所以我会在下面的代码示例中执行操作。我的想法是指定“想要”顺序,即按照我想要的类型顺序,如果它们可以适合多种类型,然后我尝试按顺序转换它们。

    public class GenericPropClass
    {
        public Type type;
        public object value;
        public string key;
    }

    [TestMethod]
    public void PropertySet()
    {
        var dict = new Dictionary<string, string>();
        var resultingList = new List<GenericPropClass>();
        // Specify the order with most "specific"/"wanted" type first and string last
        var order = new Type[] { typeof(DateTime), typeof(int), typeof(double), typeof(string) }; 

        foreach (var key in dict.Keys)
            foreach (var t in order)
            {
                try
                {
                    var res = new GenericPropClass()
                    {
                        value = Convert.ChangeType(dict[key], t),
                        key = key,
                        type = t,
                    };
                    resultingList.Add(res);
                    break;
                }
                catch (Exception)
                {
                    // Just continue
                }
            }

    }

很抱歉只收到几乎只有代码的简短回答,今晚我可能有时间改进它以获取我的想法,但我现在必须去:)