本文介绍了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>的扩展方法
发布评论