如何在C#中获取对象的小写名称(即使为null) [英] How to get the lowercase name of an object, even when null, in C#

查看:96
本文介绍了如何在C#中获取对象的小写名称(即使为null)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有C#方法

private static string TypeNameLower(object o)
{
   return o.GetType().Name.ToLower();
}

为我提供输入对象的小写类型名称。

to give me the lower case type name of the input object.

但是如果输入是设置为null的字符串或设置为null的可空int,则此方法当然会失败。

But if input is a string set to null or a nullable int set to null then this method of course fails.

在这种情况下如何获取类型名称?

How do I get the type name in this situation?

推荐答案

Jeff是正确的。就像问一个没有标签的空盒子里有什么样的蛋糕。

Jeff is correct. That's like asking what kind of cake would have been in an empty box with no label.

作为Fortran回答的替代方法,您也可以这样做:

As an alternative to Fortran's answer you could also do:

string TypeNameLower<T>(T obj) {
   return typeof(T).Name.ToLower(CultureInfo.InvariantCulture);
}

string TypeNameLower(object obj) {
   if (obj != null) { return obj.GetType().Name.ToLower(CultureInfo.InvariantCulture); }
   else { return null; }
}

string s = null;
TypeNameLower(s); // goes to the generic version

这样,C#将在编译时选择通用版本足够了解您要传递的类型。

That way, C# will pick the generic one at compile time if it knows enough about the type you're passing in.

这篇关于如何在C#中获取对象的小写名称(即使为null)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆