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

后端 未结 4 1954
孤城傲影
孤城傲影 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

    An implicit operator won't work here? If Foo is a class you can modify then I've used something like this in the past, which also allows you to compare Foo instances to a string.

    public class Foo
    {
      public string Name { get; set; }
    
      public static implicit operator Foo(string value)
      {
        return new Foo { Name = value };
      }
    }
    
    ...
    Foo foo = "fooTest";
    Console.WriteLine("Foo name: {0}", foo.Name);
    ...
    

    Edit: If you must use ChangeType then as far as I know you're out of luck. If you can modify the API to use a TypeConverter, you can use something like the following.

    ...
    Type type = typeof(Foo);
    object value = "one";
    
    var converter = TypeDescriptor.GetConverter(type);
    if (converter.CanConvertFrom(value.GetType()))
    {
      object newObject = converter.ConvertFrom(value);
      Console.WriteLine("Foo value: {0}", newObject.ToString());
    }
    ...
    
    public class FooConverter : TypeConverter
    {
      public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
      {
        return sourceType == typeof(string);
      }
    
      public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
      {
        var name = value as string;
        if (name != null)
          return new Foo { Name = name };
        else
          return base.ConvertFrom(context, culture, value);
      }
    }
    
    [TypeConverter(typeof(FooConverter))]
    public class Foo
    {
      public string Name { get; set; }
    
      public override string ToString()
      {
        return Name;
      }
    }
    

提交回复
热议问题