Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将从反射中提取的timespan格式化为仅显示小时和分钟_C#_C# 4.0_Tostring_Timespan_Typeconverter - Fatal编程技术网

C# 将从反射中提取的timespan格式化为仅显示小时和分钟

C# 将从反射中提取的timespan格式化为仅显示小时和分钟,c#,c#-4.0,tostring,timespan,typeconverter,C#,C# 4.0,Tostring,Timespan,Typeconverter,我有一个函数,我将向其传递一个匿名对象,然后我必须返回一个timespan值,该值将以hh:mm格式显示。请查看下面的代码片段 public string GetTime(Object obj, string propName) { TimeSpan? time = obj.Gettype().GetProperty(propName).GetValue(obj, null); return time.ToString(@"hh\:mm"); } 我在时间变量中得到了正确的值,当

我有一个函数,我将向其传递一个匿名对象,然后我必须返回一个timespan值,该值将以hh:mm格式显示。请查看下面的代码片段

public string GetTime(Object obj, string propName)
{
   TimeSpan? time = obj.Gettype().GetProperty(propName).GetValue(obj, null);

   return time.ToString(@"hh\:mm");
}
我在时间变量中得到了正确的值,当我尝试将其转换为字符串时,它表示no-ToString函数接受1个参数

我甚至尝试使用TimeSpan.parse进行转换,然后它允许我在这里进行转换,但它给了我错误的值作为输出

以下是我的时间跨度分析:

return TimeSpan.Parse(time.ToString()).ToString(@"hh\:mm");
我想知道如何将hh:mm作为字符串,以获得完全精确的值。 因此,请尝试以下方法:

public string GetTime(Object obj, string propName)
{
   TimeSpan? time = obj.GetType().GetProperty(propName).GetValue(obj, null);

   // The difference is here... If time has a value, then take it
   // and format it, otherwise return an empty string.
   return time.HasValue ? time.Value.ToString(@"hh\:mm") : string.Empty;
}
虽然
TimeSpan.ToString()
具有所需的重载,但
TimeSpan?
没有