C# Extension Method for Null or value

断了今生、忘了曾经 提交于 2019-12-13 22:28:55

问题


How to write an extension method that should check value of the object,if object is null then it should return null otherwise value{without doing casting at receiving end}.

something like...

public static object GetDefault(this object obj)
{
    if (obj == null) return null;
    else return obj;
}

I mean without casting can i check for null?

int? a=a.GetDefault();

ContactType type=type.GetDefault();   [For EnumType]

string  s=a.GetDefault()

回答1:


This should work:

public static class ExtensionMethods
{
    public static T GetObject<T>(this T obj, T def)
    {
        if (default(T).Equals(obj))
            return def;
        else
            return obj;
    }
}

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.



来源:https://stackoverflow.com/questions/3987986/c-sharp-extension-method-for-null-or-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!