简体   繁体   中英

C# Return Zero in Corresponding Input Type

I want a function that does this:

    private static dynamic Zero(Type T)
    {
        if (T == typeof(Decimal))
        {
            return Decimal.Zero;
        }
        else if (T == typeof(Double))
        {
            return new Double();
        }
        else if (T == typeof(Int64))
        {
            return new Int64();
        }
        ...
    }

But for all Types. I'd like to avoid writing a giant else if statement. Is there any other way to do this? I'm using C# 4.0.

return default(T);

For a value type, the default constructor would work.

if(T.IsValueType()) return Activator.CreateInstance(T);

Then you can do other stuff, like testing for a Zero method on the type and if so, calling that.

No need for dynamic here:

private static T Zero<T>()
{
    return default(T);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM