[已解决]返回Nullable基本类型/字符串的通用方法 [英] [Solved] Generic method for returning Nullable primitive types / Strings
本文介绍了[已解决]返回Nullable基本类型/字符串的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨.
我正在尝试编写一个可以返回任何可为空的原始类型或字符串的方法. I.E.
Hi.
I''m tring to write a method that can return any nullable primitive type, or a string. I.E.
public T Read<t>(string value)
{
// read code
//[...]
if (someCondition)
return null;
return (T)obj;
}
</t>
问题是我应该对T施加什么条件,以便可以返回null和可为空的基元.我不能说"where T:nullable"是可空的,而且我不能说"where T:class"是可空基元不是引用类型.
The question is what condition I should impose on T to make it so that I can return null''s and nullable primitives. I can''t say "where T : nullable" as nullable is sealed and I can''t say "where T : class" as nullable primitives aren''t reference types.
Ideas?
推荐答案
找到解决方案-使用return default(T)代替null.
Solution found - use return default(T) instead of null.
这篇关于[已解决]返回Nullable基本类型/字符串的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文