c#——扩展.net framework基本类型的功能demo -凯发k8官方网
凯发k8官方网
收集整理的这篇文章主要介绍了
c#——扩展.net framework基本类型的功能demo
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
编写一个静态类myextensions,扩展.net framework基本类型的功能。
1)定义一个扩展方法ispalindrome,方法定义为:
public static bool ispalindrome(this string str)它扩展string类的功能,用于判断字符串是否为回文(指顺读和倒读内容都一样的文本)。
2)定义一个扩展方法reversedigits,允许int将自己的值倒置,例如将整型1234调用reversedigits,返回结果为4321。
测试类如下:
class program {static void main(){string s = "abc";console.writeline($"'{s}' is {(s.ispalindrome() ? "" : "not")} palindrome");s = "abcba";console.writeline($"'{s}' is {(s.ispalindrome() ? "" : "not")} palindrome");int i = 1234;console.writeline($"reverse of {i} is {i.reversedigits()}");} } using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks;namespace homework7 {/**编写一个静态类myextensions,扩展.net framework基本类型的功能。1)定义一个扩展方法ispalindrome,方法定义为:public static bool ispalindrome(this string str)它扩展string类的功能,用于判断字符串是否为回文(指顺读和倒读内容都一样的文本)。2)定义一个扩展方法reversedigits,允许int将自己的值倒置,例如将整型1234调用reversedigits,返回结果为4321。*/static class myextensions {public static boolean ispalindrome(this string str) {for (int i = 0; i < (str.length / 2); i ) //只需要判断前一半(len/2)长度就好了{if (str[i] != str[str.length - 1 - i]) //判断是否为回文数;{return false;}}return true;}//本方法允许任何整型返回倒置的副本,例如将整型1234调用reversedigits,返回结果为4321。 public static int reversedigits(this int i){//把int 翻译为string 然后获取所有字符 char[] digits = i.tostring().tochararray();//反转数组中的项 array.reverse(digits);//放回string string newdigits = new string(digits);//最后以int返回修改后的字符串 return int.parse(newdigits);}}class program{static void main(string[] args){string s = "abc";console.writeline($"'{s}' is {(s.ispalindrome() ? "" : "not")} palindrome");s = "abcba";console.writeline($"'{s}' is {(s.ispalindrome() ? "" : "not")} palindrome");int i = 1234;console.writeline($"reverse of {i} is {i.reversedigits()}");}} }http://bbs.bccn.net/thread-463732-1-1.html
https://shentuzhigang.blog.csdn.net/article/details/89713050
总结
以上是凯发k8官方网为你收集整理的c#——扩展.net framework基本类型的功能demo的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇:
- 下一篇: c#——linq技术demo