type和nullable< type>的扩展方法 [英] extension method on type and nullable<type>

查看:111
本文介绍了type和nullable< type>的扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为简单起见,假设我要为int类型编写扩展方法?和int:

For sake of simplicity, let's assume I want to write an extension method for the type int? and int:

public static class IntExtentions
{
    public static int AddOne(this int? number)
    {
        var dummy = 0;
        if (number != null)
            dummy = (int)number;

        return dummy.AddOne();
    }

    public static int AddOne(this int number)
    {
        return number + 1;
    }
}

只能使用一种方法来完成此操作?

推荐答案

不幸的是没有。你可以做int? (或您使用的任何可为null的类型)方法都非常容易地调用non-nullable方法,因此您不需要使用2种方法来复制任何逻辑-例如

Unfortunately not. You can make the int? (or whichever nullable type you are using) method call the non nullable method very easily though, so you don't need to duplicate any logic with 2 methods - e.g.

public static class IntExtensions
{
    public static int AddOne(this int? number)
    {
        return (number ?? 0).AddOne();
    }

    public static int AddOne(this int number)
    {
        return number + 1;
    }
}

这篇关于type和nullable< type>的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆