एक Nullable.GetUnderlyingType
विधि है जो आप इस मामले में मदद कर सकते हैं नहीं है।
public static string GetTypeName(Type type)
{
var nullableType = Nullable.GetUnderlyingType(type);
bool isNullableType = nullableType != null;
if (isNullableType)
return nullableType.Name;
else
return type.Name;
}
उपयोग::
Console.WriteLine(GetTypeName(typeof(DateTime?))); //outputs "DateTime"
Console.WriteLine(GetTypeName(typeof(DateTime))); //outputs "DateTime"
संभव है कि आप अपनी खुद की उपयोगिता विधि बनाने के लिए, क्योंकि (मैं यह सोचते हैं रहा हूँ) तुम दोनों नल और गैर-व्यर्थ प्रकार का उपयोग हो जाएगा चाहते पहुंच जाएंगे
संपादित करें: मुझे लगता है तुम भी प्रकार पर अन्य तंत्र, जिस स्थिति में आप थोड़ा इस संशोधित कर सकते हैं का उपयोग कर किया जा सकता है अंतर्निहित प्रकार मिलता है या मौजूदा प्रकार का उपयोग करने अगर यह गैर-व्यर्थ है:
public static Type GetNullableUnderlyingTypeOrTypeIfNonNullable(this Type possiblyNullableType)
{
var nullableType = Nullable.GetUnderlyingType(possiblyNullableType);
bool isNullableType = nullableType != null;
if (isNullableType)
return nullableType;
else
return possiblyNullableType;
}
और वह एक भयानक एक विधि के लिए नाम है, लेकिन मैं काफी चालाक एक साथ आने के लिए नहीं कर रहा हूँ (मैं अगर किसी को एक अच्छा वाला पता चलता है इसे बदलने के लिए खुशी होगी!)
तब के रूप में
एक विस्तार विधि, अपने उपयोग की तरह हो सकता है:
public static string GetTypeName(this Type type)
{
return type.GetNullableUnderlyingTypeOrTypeIfNonNullable().Name;
}
या
typeof(DateTime?).GetNullableUnderlyingTypeOrTypeIfNonNullable().Name
स्रोत
2013-12-18 13:47:02
वास्तविक प्रकार 'Nullable' –
StuartLC
प्रश्न बाहर ले निशान है। –
एक परीक्षण के रूप में ध्यान में रखें यह ठीक है, कोड में प्रश्न चिह्न को हटाने से शायद कुछ तोड़ जाएगा। – James