开发者

C# Return Zero in Corresponding Input Type

开发者 https://www.devze.com 2022-12-17 13:35 出处:网络
I want a function that does this: private static dynamic Zero(Type T) { if (T == typeof(Decimal)) { return Decimal.Zero;

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

精彩评论

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