extending Convert.ChangeType to produce user-defined types on request

后端 未结 4 1955
孤城傲影
孤城傲影 2021-01-01 11:52

Given the class:

public class Foo
{
    public string Name { get; set; }
}

Is it possible to have a Foo instance created from a string thro

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 12:32

    Direct cast from string won't work as Dan Tao already pointed out. Could you maybe implement your own wrapper for the string and use that? Something like

    class MyString: IConvertible {
    
      public string Value { get; set; }
    
      ...
      object IConvertible.ToType(Type conversionType, IFormatProvider provider) {
        if (conversionType == typeof(Foo))
          return new Foo { Name = Value };
        throw new InvalidCastException();
      }
    
    }
    ...
    MyString myString = new MyString{Value="one"};
    Foo myFoo = (Foo)Convert.ChangeType(myString, typeof(Foo));
    

    Don't know if it is a useful idea but anyway..

提交回复
热议问题