开发者

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开发者_StackOverflow社区 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜