簡體   English   中英

如何在C#上將內置結構轉換為參數類型T?

[英]How to cast a built-in struct to a parameter type T on C#?

我正在編程一種方法來在控制台上查詢用戶的內容並得到他的答案...類似這樣的東西:

static T query<T>(String queryTxt)
    {
        Console.Write("{0} = ", queryTxt);
        T result;
        while (true)
        {
            try
            {
                result = // here should go the type casting of Console.ReadLine();
            }
            catch (FormatException e)
            {
                Console.WriteLine("Exception: {0};\r\nSource: {1}", e.Message, e.Source);
                continue;
            }
            break;
        }
        return result;
    }

簡而言之,此方法應繼續詢問queryTxt的值,其中T始終是intdouble ...

有什么好辦法嗎?

提前致謝!

如果它總是int或double可以與double.Parse一起使用,那么它將始終起作用。

使用類型轉換器

public static T Query<T>() {
    var converter = TypeDescriptor.GetConverter(typeof (T));
    if (!converter.CanConvertFrom(typeof(String)))
        throw new NotSupportedException("Can not parse " + typeof(T).Name + "from String.");

    var input = Console.ReadLine();

    while (true) {
        try {
            // TODO: Use ConvertFromInvariantString depending on culture.
            return (T)converter.ConvertFromString(input);
        } catch (Exception ex) {
            // ...
        }
    }
}

概括它的一種方法是將轉換函數作為委托傳遞。 就像是:

T query<T>(string text, Func<string, T> converter)
{... result = converter(Console.Readline())...}
query("foo", s=>Int.Parse(s));

有關更通用的方法-請閱讀“通用類型轉換” http://msdn.microsoft.com/zh-cn/library/yy580hbd.aspx和相關文章。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM