[英]How can I convert an object to a nullable generic in C#?
我有一堂課,其中包含問題的答案
答案存儲在字符串中
我創建了這樣的方法:
public void set_answer(object obj){
.....
}
這將作為一個變量,並根據問題類型將其更改為字符串表示形式,因此,例如,如果答案是字符串,則它將按原樣保留;如果答案是DateTime,則將其更改為yyyy-MM-dd格式以及大約8個其他轉換
我希望創建相反的方法,該方法將以原始類型返回答案
我有以下代碼:
public T? get_answer<T>() {
//this means that the answer has not been set yet
if (string.IsNullOrWhiteSpace(_answer)) return null;
object reply = null;
switch (_answer_type) {
...do stuff here to transform the string to the correct type, which will match T
}
<here is the problem>
}
在此代碼末尾,reply變量將包含null或類型T的變量
我該如何返回該值?
在我的代碼中,我將像這樣使用它:
DateTime? date = question.get_answer<DateTime>();
如果尚未設置答案或請求的類型不正確(即要求輸入Tupple問題的日期時間答案),則應返回null
預先感謝您可以提供的任何幫助
如果您有MyMethod<T>
並且大多數情況下,它由以下代碼組成: if (T is Type1) {...} else if (T is Type2) {...} else if [etc]
,那么通常首先您不應該使用通用方法 。
在這種情況下,我建議使用此方法:
public class MyClass
{
public string _answer;
public DateTime? GetDate()
{
DateTime result;
if (DateTime.TryParse(_answer, out result)) return result;
return null;
}
public int? GetInt()
{
int result;
if (int.TryParse(_answer, out result)) return result;
return null;
}
// etc
}
並對其進行測試:
public void TestIt()
{
var x = new MyClass { _answer = "gaga" };
var d = x.GetDate();
var i = x.GetInt();
// etc
}
或者,如果您必須使用單個對象...
public void TestIt()
{
var x = new MyClass { _answer = "gaga" };
object obj = x.GetDate();
if (obj == null) obj = x.GetInt();
// etc
}
或在一個陳述中:
public void TestIt()
{
var x = new MyClass { _answer = "gaga" };
var obj = (object) x.GetDate() ?? x.GetInt() /* ?? [etc] */ ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.