简体   繁体   English

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

[英]set property type dynamically in c#

I got the following problem with my data stream: 我的数据流出现以下问题:

The data stream consists of a dictionary, which I want to parse and specify the type of the value dynamically. 数据流由字典组成,我想解析它并动态指定值的类型。

Ie my data strea includes: 即我的数据流包括:

  • "date", "01.01.2000" “date”,“01.01.2000”
  • "name", "joe" “名字”,“乔”
  • "alive", "true" “活着”,“真实”
  • "health", "100" “健康”,“100”

Now I would like to set my properties of a generic class according to this data stream: 现在我想根据这个数据流设置泛型类的属性:

class GenericClass
{
    Hashtable genericAttributes;
}

Is there a possibility to set my values of the data stream to the correct type via reflection? 是否有可能通过反射将数据流的值设置为正确的类型?

I could try something like: 我可以尝试类似的东西:

DateTime.TryParse(date, out myDate);

for the date time object, but I don't think this will work when trying to parse doubles, floats, int16s, int32s, uint16,... 对于日期时间对象,但我不认为这将尝试解析双打,浮点数,int16s,int32s,uint16,...

Some thoughts on that? 对此的一些想法?

Thx and regards 感谢和问候

My guess from your question is that they all are IConvertible , so I would do something my code example below. 我对你的问题的猜测是,它们都是IConvertible ,所以我会做下面的代码示例。 The idea is that I specify the "want"-order, ie in the order I want the types if they can fit multiple types, and then I try to convert them in that order. 我的想法是指定“想要”顺序,即按照我想要的类型顺序,如果它们可以适合多种类型,然后我尝试按顺序转换它们。

    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
                }
            }

    }

Sorry for a short answer containing almost only code, I might have time to improve it tonight to get my thoughts in, but I have to go now :) 很抱歉只收到几乎只有代码的简短回答,今晚我可能有时间改进它以获取我的想法,但我现在必须去:)

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

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