C#: Dynamic parse from System.Type

前端 未结 6 1279
没有蜡笔的小新
没有蜡笔的小新 2020-12-23 01:59

I have a Type, a String and an Object.

Is there some way I can call the parse method or convert for that type on the string dynamically?

Basically how do I r

6条回答
  •  余生分开走
    2020-12-23 02:34

    I ran into this problem and this is how I solved it:

    value = myString;
    var parse = propType.GetMethod("Parse", new[] { typeof(string) });
    if (parse != null) {
      value = parse.Invoke(null, new object[] { value });
    }
    

    ...and it worked for me.

    To sum it up, you are trying to find a static "Parse" method on the object type that takes only one string as an argument. If you find such a method, then invoke it with the string parameter you are trying to convert. Since p is the PropertyInfo for my type, I ended this method by setting my instance with the value as follows:

    p.SetValue(instance, value, null);
    

提交回复
热议问题