Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.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/2/.net/23.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# 如何从可空类型获取字符串表示?_C#_.net_Reflection_Types - Fatal编程技术网

C# 如何从可空类型获取字符串表示?

C# 如何从可空类型获取字符串表示?,c#,.net,reflection,types,C#,.net,Reflection,Types,比如说我有 var T = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); 这是一个可为空的日期时间 T.FullName给了我: "System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neut

比如说我有

var T = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
这是一个可为空的日期时间

T.FullName
给了我:

"System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
如何从类型中提取
DateTime?
Nullable
作为字符串表示形式?

可能是这样:

var T = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
Type nullableType = Nullable.GetUnderlyingType(T);
string typeName = nullableType != null ? nullableType.Name + "?" : T.Name;

Type.FullName
返回泛型参数的完整程序集限定名。但是
ToString()
方法将打印一个更友好的名称,也许这就是您想要的:

System.Nullable`1[System.DateTime]

请注意,如果泛型参数不是来自
mscorlib
库,则
ToString
返回的类型名称可能无法通过
type.GetType(string)
方法解析。

请参阅问题:;(这个答案)我错过了,我应该删除这个问题吗?我在2年前写了一个方法就是为了这个目的()但我真的很喜欢ASh在答案中指出的解决方案!()