测试的最佳方式,如果一个泛型类型为字符串? (C#) [英] Best way to test if a generic type is a string? (c#)
问题描述
我有一个泛型类应该允许任何类型的,原始的或以其他方式。与此唯一的问题是使用默认(T)
。当你调用默认的值类型或字符串,它初始化为一个合理的值(如空字符串)。当你调用默认(T)
的对象上,则返回null。由于种种原因,我们需要确保,如果它不是原始类型,那么我们将有类型的默认实例,不可以空。这里是尝试1:
I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T)
. When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T)
on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1:
T createDefault()
{
if(typeof(T).IsValueType)
{
return default(T);
}
else
{
return Activator.CreateInstance<T>();
}
}
问题 - 字符串是不是值类型,但它没有一个参数的构造函数。那么,目前的解决方案是:
Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is:
T createDefault()
{
if(typeof(T).IsValueType || typeof(T).FullName == "System.String")
{
return default(T);
}
else
{
return Activator.CreateInstance<T>();
}
}
但是,这感觉就像一个杂牌。是否有处理字符串的情况下,更好的方式?
But this feels like a kludge. Is there a nicer way to handle the string case?
推荐答案
记住,默认值(字符串)为空,不串。空。你可能想在你的代码中一个特殊情况:
Keep in mind that default(string) is null, not string.Empty. You may want a special case in your code:
if (typeof(T) == typeof(String)) return (T)(object)String.Empty;
这篇关于测试的最佳方式,如果一个泛型类型为字符串? (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!