type和nullable< type>的扩展方法

编程入门 行业动态 更新时间:2024-10-24 01:52:31
本文介绍了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>的扩展方法

本文发布于:2023-11-11 06:57:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577699.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   nullable   type   amp   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!