我嘗試一般轉換用戶輸入簡單或複雜的類型一般System.String要任何複雜類型:轉換使用「Convert.ChangeType()」
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; }
}
有關轉換到我的「用戶」類,我總是得到異常「從'System.String'轉換爲'ConsoleApplication1.User'。」。有誰知道如何解決這一問題?
如果我嘗試這樣的事情(不一般),它只是完美:
Console.WriteLine((string) ((User) "Peggy Sue"));
User對象是否提供默認構造函數? – 2011-03-23 07:03:13