使用"Convert.ChangeType()"将System.String一般转换为任何复杂类型

Mai*_*aik 5 c# string type-conversion

我尝试将用户输入一般转换为简单或复杂类型:

class Program
{
  static void Main(string[] args)
  {
    Console.WriteLine("Welcome, please provide the following info... Confirm with <RETURN>!");
    Console.WriteLine();    

    Console.Write("Name (e.g. 'Peggy Sue'): ");
    var user = GetUserInput<User>(Console.ReadLine());

    Console.WriteLine();
    Console.WriteLine();
    Console.WriteLine("Hi {0}, nice to meet you!", user.Forename);
    Console.WriteLine();

    Console.Write("Age: ");
    user.Age = GetUserInput<ushort>(Console.ReadLine());

    Console.WriteLine();
    Console.WriteLine("Thanks and goodbye!");
    Console.WriteLine("Press <RETURN> to quit...");
    Console.ReadLine();
  }

  static T GetUserInput<T>(string data)
  {
    return (T) Convert.ChangeType(data, typeof (T));
  }
}

class User
{
  public User(string name)
  {
    var splitted = name.Split(' ');
    Forename = splitted[0];
    Lastname = splitted[1];
  }

  public static implicit operator User (string value)
  {
    return new User(value);
  }

  public static explicit operator string (User value)
  {
    return string.Concat(value.Forename, " ", value.Lastname);
  }

  public string Forename { get; private set; }
  public string Lastname { get; private set; }

  public ushort Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

为了转换到我的"User"类,我总是得到异常"从'System.String'到'ConsoleApplication1.User'的无效转换.".有谁知道如何解决这一问题?

如果我尝试这样的东西(不是一般),它的工作就完美了:

Console.WriteLine((string) ((User) "Peggy Sue"));
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

不,Convert.ChangeType只适用于一组固定的类型,我相信......或者如果原始对象实现IConvertible,它可以调用IConvertible.ToType.这意味着你可以IConvertible在你的User班级实施并拥有

Convert.ChangeType(user, typeof(string))
Run Code Online (Sandbox Code Playgroud)

工作,但这不会相反.

您是否有需要转换的固定类型?如果是这样,您可以Dictionary<Type, Func<string, object>>使用转换委托填充.然后你只需要调用适当的转换并转换返回值.这很难看,但可能是你最好的选择.


Mar*_*ell 5

这里的一个选择可能是将TypeConverter与您关注的类型相关联(您可以在编译时通过此方法执行此操作[TypeConverter(...)],或者如果您不控制类型,则可以在运行时执行此操作).

然后它是:

TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
T obj = (T)conv.ConvertFromString(text); // or ConvertFromInvariantString
Run Code Online (Sandbox Code Playgroud)