本文介绍了空或值的C#扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何编写应检查对象值的扩展方法,如果object为null,则它应该返回null,否则返回值{不进行接收端的强制转换}.
How to write an extension method that should check value of the object,if object is null thenit should return null otherwise value{without doing casting at receiving end}.
类似...
public static object GetDefault(this object obj)
{
if (obj == null) return null;
else return obj;
}
我的意思是,如果不进行强制转换,我可以检查null吗?
I mean without casting can i check for null?
int? a=a.GetDefault();
ContactType type=type.GetDefault(); [For EnumType]
string s=a.GetDefault()
推荐答案
这应该有效:
public static class ExtensionMethods
{
public static T GetObject<T>(this T obj, T def)
{
if (default(T).Equals(obj))
return def;
else
return obj;
}
}
我添加了一个参数def
,因为我希望您想在obj为null时返回此默认值.否则,您总是可以忽略T def
参数,而返回null
.
I've added a parameter def
because I expected you to want to return this default value when obj is null. Otherwise, you can always leave out the T def
parameter and return null
instead.
这篇关于空或值的C#扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!