2016-12-01 81 views
0

我有一个类,它包含了问题如何将对象转换为C#中可为空的泛型?

的答案回答存储在一个字符串

我创建了一个方法,像这样:

public void set_answer(object obj){ 
    ..... 
} 

这将作为arguement变量,并根据该问题的类型将其转换为一个字符串表示,因此,例如,如果答案是一个字符串,将保持,因为它是,如果它是一个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> 
} 

在该代码的结束时,应答变量将包含任一空或T类型的变量

我怎么能返回值?

在我的代码

我会用这样的:

DateTime? date = question.get_answer<DateTime>(); 

如果没有谜底尚未设置或请求是不正确的类型,应返回null(即要求一个日期时间回答上一个元组的问题)

预先感谢任何帮助,您可以提供

+2

应用.NET命名[约定](https://msdn.microsoft.com/en-us/library/ms229043(V = vs.110)的.aspx),F.E. 'set_answer'->'SetAnswer','get_answer'->'GetAnswer' –

+0

你只是想返回'新的可空(值)'? – DavidG

+1

蒂姆我试过了,似乎没有解决我的问题,DavidG基本上我想让来电者发出一个请求,说“给我这个形式的答案”,如果问题有答案,那个答案可以转换为THAT形式,那么它应该返回在这种形式(整数,日期,元组,列表和其他人)的答案,否则它应该返回null – Cruces

回答

0

如果你有MyMethod<T>并在大多数情况下它是由像if (T is Type1) {...} else if (T is Type2) {...} else if [etc]代码,那么很多时候你应该不是b首先使用通用方法

在这种情况下,我会建议使用此:

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 
} 

或者,如果你必须使用一个单一的obj ...

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] */ ; 
} 
+0

好吧我的方法更像 if( T是Type1 && _question_type是QuestionTypes。) 但是我明白你在说什么,我想我会改变它,看起来比较干净谢谢 – Cruces

相关问题